Is there a good way to declare that a function ret...
# announcements
a
Is there a good way to declare that a function returns a nonnull type, where the generic used is nullable? For instance:
Copy code
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?
r
maybe something like
fun <T: Any> Call<T?>.callNotNull(): T
helps?
a
That would cause
nonnullCall.callNotNull()
to fail as the signature is
Call<T>
instead of
Call<T?>
r
It was more about an idea not a solution. You could use
Call<out T?>
.callNotNull()` but that depends on your use case of course