9
我有以下的Java接口:更换SAM-构造与拉姆达与协变型
interface Action1<T> {
void call(T t);
}
interface Test<T> {
void test(Action1<? super T> action)
}
而下面的科特林类:
interface A {
fun go()
}
abstract class Main {
abstract fun a(): Test<out A>
fun main() {
a().test(Action1 { it.go() })
a().test { it.go() }
}
}
在功能
main
现在,第一条语句编译,但IntelliJ给出了一个警告,即SAM构造函数可以用lambda替换。 这将导致第二个陈述。
但是,第二条语句不编译,因为it
的类型为Any?
,而不是A
。删除out
修饰符使其再次编译。
这是为什么发生?
的这种使用情况是实现类的Main
需要返回的功能a()
,其中B
实现A
:
class B : A {
override fun go() {
TODO()
}
}
class MainImp : Main() {
override fun a(): Test<out A> {
val value: Test<B> = object : Test<B> {
override fun test(action: Action1<in B>?) {
TODO()
}
};
return value
}
}