我有以下代码(这里是Kotlin Playground 的链接):
import kotlinx.coroutines.*
sealed class CallResult<out T : Any> {
data class Success<out T : Any>(val data: T) : CallResult<T>()
data class Failure(val error: String) : CallResult<Nothing>()
}
public data class Response<T>(val body: T?)
suspend fun <T : Any> f1(lambda: suspend () -> Response<T>): T = when(val result = f3(lambda())) {
is CallResult.Success -> result.data
is CallResult.Failure -> throw Exception()
}
fun <T : Any> f3(response: Response<T>): CallResult<T> {
val body = response.body
if (body != null) {
return CallResult.Success(body)
} else {
return CallResult.Failure("error")
}
}
fun f4(): Response<Any> {
return Response(Any())
}
fun main() {
GlobalScope.launch {
f1 { f4() }
}
print("done!")
}
此代码在 Kotlin 1.3.72 中编译并运行良好,但在 Kotlin 1.4.30中出现以下编译错误,表示f4()
无法调用f1
:
Type mismatch: inferred type is Response<Any> but Response<Unit> was expected
Type mismatch: inferred type is Any but Unit was expected
有趣的事实:这只发生在它是 lambda 中的最后一次调用(使其成为返回结果)时,否则它也在 1.4 中编译:
GlobalScope.launch {
f1 { f4() }
print("test") // adding this makes it compile in 1.4
}
有人可以解释一下1.4中的哪些更改导致它开始无法编译吗?