【问题标题】:Define an object as subtype of a generic sealed class?将对象定义为通用密封类的子类型?
【发布时间】:2018-04-20 11:22:23
【问题描述】:

我有以下类层次结构:

sealed class SubscriptionServiceResponse<T>
data class UserRecognized<T>(val recognizedUser: RecognizedUser, val response: T) : SubscriptionServiceResponse<T>()
data class UserNotRecognized<T>(val ignored: Boolean = true) : SubscriptionServiceResponse<T>()

但是,我更喜欢 UserNotRecognized 而不是 object - 类似于:

object UserNotRecognized : SubscriptionServiceResponse()

ignored 参数就在那里,因为我无法在没有任何参数的情况下创建数据类。

有没有办法将object 定义为泛型sealed class 的子类型?

【问题讨论】:

  • 您遇到了什么问题?你的例子对我来说似乎很好
  • UserNotRecognizedobject 的版本无法编译 - 正如我所说,在这种情况下,我真的不需要任何 content,@ 987654330@ 只是为了满足编译器...
  • 对象的泛型类型对逻辑是否重要?还是Any 输入够了?
  • 是的,对于UserRecognized 的情况,它很重要——我想要UserRecognized&lt;SubscriptionStatus&gt;UserRecognized&lt;PurchaseOptions&gt; 等。
  • 好吧,也许我弄错了,但是您的 UserNotRecognized 的类型并不是很重要,因为您没有将其视为有用的数据。

标签: kotlin


【解决方案1】:

您可以使用AnyAny?,仅忽略不响应的泛型类型。从您的问题来看,我了解到您并不关心对象的泛型类型,所以也许您根本不关心它

类似这样的:

sealed class SubscriptionServiceResponse<T> {
    data class UserRecognized<T>(val bool: Boolean) : SubscriptionServiceResponse<T>()
    object UserNotRecognized : SubscriptionServiceResponse<Any?>()
}

【讨论】:

  • 啊,是的 - 谢谢!事实上,我昨天已经尝试过了,但以下内容仍然没有编译:fun someResponse() : SubscriptionServiceResponse&lt;String&gt; = UserNotRecognized - 但是如果我这样写:fun someResponse() : SubscriptionServiceResponse&lt;String&gt; = UserNotRecognized as SubscriptionServiceResponse&lt;String&gt;,一切都很好!
  • 如果声明sealed class SubscriptionServiceResponse&lt;in T&gt;,则不需要演员表。
  • @AlexeyRomanov:完美,这是缺失的部分!非常感谢!
【解决方案2】:

您可以像这样指定泛型类型:

object UserNotRecognized : SubscriptionServiceResponse<Any>()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 2017-01-22
    • 1970-01-01
    • 2016-06-26
    • 2020-04-26
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    相关资源
    最近更新 更多