我正在嘗試掌握 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) {}
}
你能解釋一下為什么它不能編譯嗎?
uj5u.com熱心網友回復:
您宣告它T必須是A.
讓我們用一個更形象的例子。假設A是 aPerson并且T是 a Teacher。您已經宣告 aTeacher是 a Person- 這是有道理的。然而,事實并非如此。并非所有Person的 s ( A) 都是Teachers ( T)。
呼叫兩者時bar,callable您希望 aTeacher被傳入。
您不能簡單地用Personor呼叫這些函式A,因為那個人可能不是Teacher(or T)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437849.html
上一篇:使用Rust空型別作為泛型系結
下一篇:Jackson解碼泛型型別
