Jack
Jack

Reputation: 1575

passing a generic type to a nested sealed class

Is it possible? How can I expain to the compiler that its the same type (BR) extending the same class? The code bellow fails

class BaseRepository<BR: BaseResponse>() {

sealed class BaseSealedResponse {
    open class Success(val receivedValue: BR)
    open class RequestError(val error: HttpException)
}
}

Upvotes: 2

Views: 1749

Answers (1)

hotkey
hotkey

Reputation: 147981

No, that's not possible. Only inner classes can refer to type parameters of the outer type. A sealed class cannot be marked as inner, so it can only access its own type parameters:

class BaseRepository<BR: BaseResponse>() {
    sealed class BaseSealedResponse {
        open class Success<B: BaseResponse>(val receivedValue: B)
        open class RequestError(val error: HttpException)
    }
}

You can define a member function inside BaseRepository that creates instances of Success parameterized with BR:

fun Success(receivedValue: BR) = BaseSealedResponse.Success(receivedValue)

Upvotes: 2

Related Questions