Kotlin中的型變:
1. in,顧名思義,就是只能作為傳入參數的參數類型
2.out, ..............,就是只能作為返回類型參數的參數類型
星號投影:
我們引用官網的吧--
- For
Foo<out T>, whereTis a covariant type parameter with the upper boundTUpper,Foo<*>is equivalent toFoo<out TUpper>. It means that when theTis unknown you can safely read values ofTUpperfromFoo<*>.
就是說返回參數類型可以不具體指定,用*號來引用上界即可,也就是我們用Any類型就行,它的含義Foo<*>=Foo<out Any>
好吧,我給個例子,里邊有型變和投影,型變的概念是確定無疑,但是星號投影就是扯蛋,kotlin說了"我們還不成熟"
// 1
我們老老實實的寫寫
interface MyIfe<out C, in D> {
fun MyFun(d: D) {
println(d)
}
}
class MyClsEx<out A, in B>(val a:A, b:B):MyIfe<Any,Int> {
init {
println(b)
}
fun foo():A {
return a
}
}
fun main(args: Array<String>) {
val res = MyClsEx<Any,Int>("Any", 13)
println("${res.a}+b refering to ahead")
res.MyFun(1)
}
result:
Any+b refering to ahead
1
Ok, 沒問題
// 2
我們用上星號投影吧
interface MyIfe<out C, in D> {
fun MyFun(d: D) {
println(d)
}
}
class MyClsEx<out A, in B>(val a:A, b:B):MyIfe<*,Int> {
init {
println(b)
}
fun foo():A {
return a
}
}
fun main(args: Array<String>) {
val res = MyClsEx<Any,Int>("Any", 13)
println("${res.a}+b refering to ahead")
res.MyFun(1)
}
//編譯就錯誤
error: projections are not allowed for immediate arguments of a supertype
class MyClsEx<out A, in B>(val a:A, b:B):MyIfe<*,Int> {
扯蛋第一步產生了,這個星號根本不能用嘛
// 3
怎么辦呢?
看看官網,For example, if the type is declared as interface Function<in T, out U> we can imagine the following star-projections
其中interface Function讓我想到----“可能在泛型函數中能實現星號投影”
所以
interface MyIfe {
fun <out C, in D> MyFun(d: D) {
println(d)
}
}
class MyClsEx<out A, in B>(val a:A, b:B):MyIfe {
init {
println(b)
}
fun foo():A {
return a
}
}
//編譯也錯誤
error: projections are not allowed for immediate arguments of a supertype
class MyClsEx<out A, in B>(val a:A, b:B):MyIfe<*,Int> {
//結論
泛型三大類別,(類,接口)和函數全都不能星號投影,那么你認為還能投影嗎?
我認為不能
Finally:
但我就是對Kotlin有信心,就是這么固執,乍辦呢!
哈哈哈
