Kotlin Contracts

I have a question regarding Kotlin Contracts.

Background

I have a sealed class that can be two types:

sealed class ApiResponse<out T> {
data class Success<out T>(val response: T) : ApiResponse<T>()
data class Error(
val code: Int? = null,
val message: String? = null,
val response: ErrorResponse? = null
) : ApiResponse<Nothing>()
}

Problem

Casting every time I need to read response: T is tedious.

val networkResponse = getResponse()

if(networkResponse is ApiResponse.Success<SomeType>) {}

Solution

Because of this I decided to use kotlin contract api and wrote function like this.

u/OptIn(ExperimentalContracts::class)
fun isSuccessful(): Boolean {
contract {
returns(true) implies (this@ApiResponse is Success<T>)
}
return this is Success<T>
}

Problem with this approach is that when I write

if (networkResponse.isSuccessful()) {

//here networkResponse.response is T not SomeType

}

Any ideas how can I fix it?

submitted by /u/RichAd1495
[link] [comments]