https://kotlinlang.org logo
#announcements
Title
# announcements
r

Rafa

09/03/2019, 11:55 PM
Playing around with generics in Kotlin, and thought this was interesting
Copy code
class Example<T>(private val source: T){
    fun test(value: T?): T? = value
}

fun <T> create() = Example(null)
If we define the class to take in a non-nullable generic type, and still pass in null,
Example(null)
then the generic resolves to
Example<Nothing?>
. If we make the generic nullable
T?
then it resolves to
Example<Nothing>
. I can't find anything online that confirms that null on a generic type returns "Nothing" and I guess it kind of make sense, but can anyone confirm as to how that happens?
to more directly answer your question, though, because `Nothing`and
Nothing?
are the “bottom” of the type system, the type of
null
as a literal parameter, absent any sort of annotation or projection that can tell the compiler that it is supposed to represent some other nullable type, has to resolve to
Nothing?
p

Pavlo Liapota

09/04/2019, 5:54 AM
Also note, that by default all generic types extend
Any?
, i.e.
T : Any?
, so
T
can be nullable. You need to write
Copy code
class Example<T : Any>
if you want that
T
can be non-nullable type only. Then it would make sense to use
T?
in a function inside your class.
r

Rafa

09/04/2019, 2:25 PM
Thanks for the answers and the resources!
4 Views