Is there a good way to declare that a function returns a nonnull type, where the generic used is nullable?
For instance:
interface 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?