简体   繁体   中英

Sealed class generics in kotlin not related to inner classes

I want to have an ApiResponse with some generic type to know what type will contain in case of success, something like:;

I mean, what I pretend is:

sealed class ApiResponse<T> {
  class Success<T>(body: T)
}

fun getUsers(): ApiResponse<List<User>>

And then when I call getUsers I know that it may contain a ApiResponse.Success<List<User>> .

But T from ApiResponse<T> is not related to Success<T> since I can write it like:

sealed class ApiResponse<NotUsed> {
  class Success<T>(body: T)
}

And then I create a function that returns an ApiResponse like:

fun getUsers(): ApiResponse

I dont know which kind of object that response may contain if it was a success.

How can I do it?

Your Success class isn't related to your ApiResponse class in any way other than being scoped inside of it. If you want the Success to be an ApiResponse , you should do something like this, which will also relate the generic types:

sealed class ApiResponse<T> {
    class Success<T>(body: T) : ApiResponse<T>()  // Success extends ApiResponse
}

Note that they only have to be in the same file, not necessarily nested (since Kotlin 1.1), so the following will also work:

sealed class ApiResponse<T>

class Success<T>(body: T) : ApiResponse<T>()  // Success extends ApiResponse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM