0

Misc.kts contains:

class E
fun <B> foo(): B {
    return E() // <--- Error here
}
fun bar() {
    val r = foo<E>()
}

Error is Type mismatch: inferred type is Misc.E, but B was expected. This compiler behavior surprises me. I'd be grateful for an explanation.

1 Answer 1

6

You can think of generic functions as cookie cutters for functions. For any value of B, your generic function definition can stamp out a different function cookie.

There is one value of B that can make return E() legal. That's when B is E, which is the case in the call too foo<E>(). However, this is the only such case. What happens if I call foo<Int>()? You can't return an E() when an Int is expected.

For your function definition to be valid, it's insufficient for there to merely exist one return value which is compatible with B. Your returned value must be compatible with all possible values of B.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.