Allan Wang
06/20/2019, 6:24 PMinterface Call<T> {
suspend fun call(): T
}
suspend fun <T> Call<T>.callNotNull(): T = call() ?: throw RuntimeException("Example")
val nonnullCall = object : Call<String> {
override suspend fun call(): String = "notnull"
}
val nullCall = object : Call<String?> {
override suspend fun call(): String? = null
}
suspend fun t() {
val r: String = nonnullCall.callNotNull()
val s: String = nullCall.callNotNull()
}
At its current state, I will get an error for nullCall
since s
is String?
Type T
may or may not be nullable, but the returning type is definitely not null.
I can’t use contracts because this is a suspended function
I can’t make the extension to Call<T?>
or it won’t work for nonnullCall
Do I have to make two extension functions for this to work? Is there something like T!
that would indicate a type with nullability removed?robstoll
06/20/2019, 6:29 PMfun <T: Any> Call<T?>.callNotNull(): T
helps?Allan Wang
06/20/2019, 6:29 PMnonnullCall.callNotNull()
to fail as the signature is Call<T>
instead of Call<T?>
robstoll
06/20/2019, 6:31 PMCall<out T?>
.callNotNull()` but that depends on your use case of course