Kotlin 型变 + 星号投影(扯蛋)

Kotlin中的型变:

1. in,顾名思义,就是只能作为传入参数的参数类型

2.out, ..............,就是只能作为返回类型参数的参数类型

星号投影:

我们引用官网的吧--

  • For Foo<out T>, where T is a covariant type parameter with the upper bound TUpper, Foo<*> is equivalent to Foo<out TUpper>. It means that when the T is unknown you can safely read values of TUpper from Foo<*>.

就是说返回参数类型可以不具体指定,用*号来引用上界即可,也就是我们用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有信心,就是这么固执,乍办呢!

 

哈哈哈

 

转载于:https://www.cnblogs.com/woodzcl/p/7700768.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值