Home > Software design >  Kotlin: Generic high-order function - Type mismatch
Kotlin: Generic high-order function - Type mismatch

Time:02-24

I'm trying to grasp generics in Kotlin.

In the following sample, I'm trying to constrain the type T and use it inside a high-order function, or just functions in general.

interface A {
    fun foo()
}

class bar<T : A> (val g: A, val h: T, val callable: (T) -> Unit ) {
    fun test() {
        // Polymorphism works as expected
        g.foo()
        h.foo()

        // Type mismatch: inferred type is A but T was expected
        callable(g)

        // Fine
        callable(h)
        
        // Type mismatch: inferred type is A but T was expected
        baz(g)

        // Fine
        baz(h)
    }
    
    fun baz(l: T) {}
}

Could you please explain why it doesn't compile?

CodePudding user response:

You declared that T must be a supertype of A.

Let's use a more graphic example. Assume A is a Person and T is a Teacher. You've declared that a Teacher is a Person - which makes sense. However, the opposite is not true. Not all Persons (A) are Teachers (T).

When invoking both bar and callable you expect a Teacher to be passed in.

You cannot simply call these functions with a Person or A, because that person might not be a Teacher (or T).

  • Related