david.mihola
david.mihola

Reputation: 12992

Define an object as subtype of a generic sealed class?

I have the following class hierarchy:

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>()

However, I'd prefer UserNotRecognized to just be an object - something like:

object UserNotRecognized : SubscriptionServiceResponse()

(The ignored parameter is just there because I can't make a data class without any parameters).

Is there any way to define an object as the subtype of a generic sealed class?

Upvotes: 4

Views: 1553

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81939

You can specify the generic type like this:

object UserNotRecognized : SubscriptionServiceResponse<Any>()

Upvotes: 2

LeoColman
LeoColman

Reputation: 7133

You can use Any or Any?, ignoring the generic type for the non-response only. As from your question, I understood that you're not caring about the generic type of your object, so maybe you can not care about it at all

Something like this:

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

Upvotes: 4

Related Questions