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
的超类型。
让我们使用一个更形象的例子。
假设 A
是 Person
,T
是 Teacher
。您已经声明 Teacher
是 Person
- 这是有道理的。然而,事实并非如此。并非所有 Person
s (A
) 都是 Teacher
s (T
)。
同时调用 bar
和 callable
时,您希望传入 Teacher
。
您不能简单地用 Person
或 A
调用这些函数,因为那个人可能不是 Teacher
(或 T
)。
我正在尝试掌握 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
的超类型。
让我们使用一个更形象的例子。
假设 A
是 Person
,T
是 Teacher
。您已经声明 Teacher
是 Person
- 这是有道理的。然而,事实并非如此。并非所有 Person
s (A
) 都是 Teacher
s (T
)。
同时调用 bar
和 callable
时,您希望传入 Teacher
。
您不能简单地用 Person
或 A
调用这些函数,因为那个人可能不是 Teacher
(或 T
)。