A quick questions on generics. Is it possible to e...
# announcements
m
A quick questions on generics. Is it possible to enforce non-nullable type from a nullable type? Something like this:
Copy code
class Foo<T: Any?> {
  
    abstract fun returnValue(): T
    abstract fun returnValueAsNonNullable(): T!! // this doesn't work 

}
The problem is I need to define the T type as either nullable or non-nullable, but I'm trying to bridge semantics of reactive streams, which are always non-nullable and represent
null
by empty stream state, and futures which are possibly nullable. However I need to differentiate between a nullable and non-nullable future, therefore decide whether to allow the reactive stream to return empty value (as null) or fail.
m
Why not?:
Copy code
class Foo<T: Any> {
    abstract fun returnValue(): T?
    abstract fun returnValueAsNonNullable(): T
}
m
because that would make
returnValue()
always nullable, which is not what I want. I want the this function to be either nullable or non-nullable based on the developer desire. However need to return always non-nullable from
returnValueAsNonNullable
s
Btw
T: Any?
is same as
T
👍 1
m
I wanted to be explicit there.
but pretty much need to define a possibly nullable type
T
as non-nullable version of itself
u
T!!
will be possible since Kotlin 1.6
👍 5
m
This is a great news, but is there any pattern I could follow in the meantime?
f
You can solve it with an extension function but that's useless for your exact use case because it cannot be abstract. I fear there's no way ... well ... unless you use two type parameters.
Foo<A : Any, B : A?>
1