Kotlin:通用高阶函数 - 类型不匹配

Kotlin: Generic high-order function - Type mismatch

我正在尝试掌握 Kotlin 中的泛型。

在下面的示例中,我试图限制类型 T 并在高阶函数中使用它,或者只是在一般函数中使用它。

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) {}
}

你能解释一下为什么它不能编译吗?

您声明 T 必须是 A 的超类型。

让我们使用一个更形象的例子。 假设 APersonTTeacher。您已经声明 TeacherPerson - 这是有道理的。然而,事实并非如此。并非所有 Persons (A) 都是 Teachers (T)。

同时调用 barcallable 时,您希望传入 Teacher

您不能简单地用 PersonA 调用这些函数,因为那个人可能不是 Teacher(或 T)。