Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define an object as subtype of a generic sealed class?

Tags:

kotlin

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?

like image 570
david.mihola Avatar asked Sep 21 '25 03:09

david.mihola


2 Answers

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?>()
}
like image 173
LeoColman Avatar answered Sep 22 '25 20:09

LeoColman


You can specify the generic type like this:

object UserNotRecognized : SubscriptionServiceResponse<Any>()
like image 37
s1m0nw1 Avatar answered Sep 22 '25 20:09

s1m0nw1