Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make generic type of Assertion.Builder covariant #303

Open
zarebski-m opened this issue Sep 18, 2024 · 0 comments
Open

Make generic type of Assertion.Builder covariant #303

zarebski-m opened this issue Sep 18, 2024 · 0 comments

Comments

@zarebski-m
Copy link

Currently T in Assertion.Builder is invariant. Is there a specific reason for that?

I have stumbled upon a problem with a custom assertion I was writing. I have a structure which is essentially a tree of maps:

data class Node(id: String, children: MutableMap<String, Node>)

fun buildTree(): Map<String, Node> = TODO("irrelevant")

I wanted to create two assertions:

fun Assertion.Builder<Map<String, Node>>.node(
    id: String,
    childrenAssertion: Assertion.Builder<Map<String, Node>>.() -> Unit
) {
    withValue(id) {
        get { this.id }.isEqualTo(id)
        get { children }.childrenAssertion()
    }
}

fun Assertion.Builder<Map<String, Node>>.leaf(id: String) {
    withValue(id) {
        get { this.id }.isEqualTo(id)
        get { children }.isEmpty()
    }
}

// usage
expectThat(buildTree()) {
    node("node1") {
        node("node2") {
            leaf("leaf1")
        }
        leaf("leaf2")
        leaf("leaf3")
    }
}

But it didn't work because childrenAssertion binds T to Map<*, *> where get { children } returns builder with T bound to MutableMap<*, *>. The solution was to use call-site projection:

fun Assertion.Builder<out Map<String, Node>>.node(
    id: String,
    childrenAssertion: Assertion.Builder<out Map<String, Node>>.() -> Unit
)

But then I wondered why Assertion.Builder is not covariant in the first place? What would be the drawbacks of defining it as Assertion.Builder<out T>?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant