用协变类型替换带有lambda的SAM构造函数
我有以下的Java接口:
interface Action1<T> { void call(T t); } interface Test<T> { void test(Action1<? super T> action) }
以下Kotlin课程:
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()
Test<B>
,其中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 } }
这是一个编译器错误。 你可以在这里跟踪: https : //youtrack.jetbrains.com/issue/KT-12238 。