当我编写通用密封类时,我发现了有趣的事情。这是第一个版本:
// sample interface and implementation
interface MyInterface
class MyInterfaceImpl : MyInterface
sealed class Response<T: MyInterface>
data class Success<T: MyInterface>(val payload: T) : Response<T>()
data class Failure(val errorCode: Int) : Response<MyInterface>()
object Cancelled : Response<MyInterface>()
假设我们也有这样的请求功能:
fun <T: MyInterface> requestObject(cls : KClass<T>): Response<T> = TODO("Request")
现在在使用方面我们有错误:
fun test() = when (val response = requestObject(MyInterfaceImpl::class)) {
is Success -> print("Payload is ${response.payload}") // Smart cast perfectly works!
is Failure -> print("Error code ${response.errorCode}") // Incomparable types: Failure and Response<MyInterfaceImpl>
Cancelled -> print("Request cancelled") // Incomparable types: Cancelled and Response<MyInterfaceImpl>
}
第一个问题:
Failure
并且Cancelled
不T
用于进/出位置,为什么这个演员没有被检查,我需要压制它?
过了一会儿,康斯坦丁向我展示了如何声明类型安全的密封类的解决方案:
sealed class Response<out T: MyInterface> // <-- out modifier here
data class Success<T: MyInterface>(val payload: T) : Response<T>()
data class Failure(val errorCode: Int) : Response<Nothing>() // <-- Nothing as type argument
object Cancelled : Response<Nothing>() // <-- Nothing as type argument
这个声明就像一个魅力,现在我有问题:
第二个问题:为什么要
out
在这里写修饰符?第三个问题:为什么
Producer<Nothing>
是亚型Producer<MyInterface>
?根据协变的定义:Producer<A>
是Producer<B>
if的子类型的A
子类型B
,但Nothing
不是 的子类型MyInterface
。它看起来像未记录的语言外功能。