2

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)
}
}
Jack
  • 1,545
  • 2
  • 11
  • 20

1 Answers1

2

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)
hotkey
  • 140,743
  • 39
  • 371
  • 326
  • You can declare the sealed class in the way I provided in the answer and then define a factory function inside `BaseRepository`: `fun Success(receivedValue: BR) = BaseSealedResponse.Success(receivedValue)`. This will let you directly create instances of `Success` parameterized with `BR`. – hotkey Mar 20 '18 at 22:24
  • that really doesnt do the trick ( I guess you cannot combined sealed classes logic with generics ((( – Jack Mar 20 '18 at 22:49
  • Parametrize `BaseSealedResponse` and make sure it's only created with the same parameter inside `BaseRepository`. – Alexey Romanov Mar 21 '18 at 06:14