Kotlin 将对象定义为泛型密封类的子类型?

Kotlin 将对象定义为泛型密封类的子类型?,kotlin,Kotlin,我有以下类层次结构: sealed class SubscriptionServiceResponse<T> data class UserRecognized<T>(val recognizedUser: RecognizedUser, val response: T) : SubscriptionServiceResponse<T>() data class UserNotRecognized<T>(val ignored: Boolean =

我有以下类层次结构:

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>()
(忽略的
参数就在那里,因为我无法创建没有任何参数的数据类)


是否有任何方法将
对象定义为泛型
密封类的子类型

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

大概是这样的:

sealed class SubscriptionServiceResponse<T> {
    data class UserRecognized<T>(val bool: Boolean) : SubscriptionServiceResponse<T>()
    object UserNotRecognized : SubscriptionServiceResponse<Any?>()
}
object UserNotRecognized : SubscriptionServiceResponse<Any>()
密封类订阅服务响应{
数据类userrecogned(val bool:Boolean):SubscriptionServiceResponse()
对象UserNotRecognited:SubscriptionServiceResponse()
}

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

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

您面临的问题是什么?你的例子对我来说似乎很好,
UserNotRecognized
是一个
对象的版本
没有编译-正如我说的,我真的不需要任何内容在这种情况下,
布尔值
只是为了满足编译器的需要…你的对象的泛型对逻辑重要吗?或者
任何
类型都足够了吗?是的,对于
用户识别
的情况来说,这很重要-我想让
用户识别
用户识别
,等等。好吧,也许我弄错了,但是您的用户未识别的类型不是很重要,因为您没有将其视为有用的数据。啊,是的-谢谢!事实上,我昨天已经试过了,但是下面的代码仍然没有编译:
fun-someResponse():subscriptionservicesponse=UserNotRecognized
-但是如果我这样写:
fun-someResponse():subscriptionservicesponse=UserNotRecognized as-subscriptionservicesponse
,一切都很好!如果您声明
密封类订阅服务响应
,则不需要强制转换。@AlexeyRomanov:太好了,这就是缺少的部分!非常感谢你!