Rafa
09/03/2019, 11:55 PMclass 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?Shawn
09/04/2019, 12:25 AMNothing?
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?
Pavlo Liapota
09/04/2019, 5:54 AMAny?
, i.e. T : Any?
, so T
can be nullable.
You need to write
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.Rafa
09/04/2019, 2:25 PM