gpt4 book ai didi

generics - 通用密封类的类型安全用法

转载 作者:行者123 更新时间:2023-12-02 13:36:42 26 4
gpt4 key购买 nike

当我编写通用密封类时,我发现了有趣的事情。这是第一个版本:

// 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>
}

First question: Failure and Cancelled isn't use T for in/out positions, why this cast is unchecked and I need to suppress it?


不久后, Konstantin向我展示了如何声明类型安全密封类的解决方案:
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
这个声明就像一个咒语,现在我有疑问:

Second question: why it's necessary to write out modifier here?

Third question: why Producer<Nothing> is subtype of Producer<MyInterface>? By definition of covariant: Producer<A> is subtype of Producer<B> if A subtype of B, but Nothing isn't subtype of MyInterface. It looks like undocumented extralinguistic feature.

最佳答案

差异最终无法解决。 Response<MyInterfaceImpl>不是Response<MyInterface>,因此无法使用FailureCancelled。即使您没有使用gerneric类型,您仍然可以声明它。

放置out T时,您将获得类似于Java中的? extends T的效果。

然后对于 Nothing 您有:

Nothing has no instances. You can use Nothing to represent "a value that never exists".



这也意味着它是所有内容的子类型,因此也适用于泛型。

关于generics - 通用密封类的类型安全用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54804289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com