May be stupid but a junior dev here 😄
Is there a particular good reason to have a generic function parameter type inherit from “Any”?
In the image, the method we use, and the second one is without it.
d
Drew Hamilton
02/12/2020, 12:12 PM
In the second one,
T
can be a nullable type. In the first one, it can’t be.
👍 1
w
wcaokaze
02/12/2020, 12:24 PM
Yep. In other words,
<T>
means
<T : Any?>
👍 1
o
Ofir Bar
02/12/2020, 12:27 PM
Hmm.. didn’t expect that.
So by default, Kotlin generics allow nulls.. isn’t that goes against how Kotlin tries to fight NPE?
I would expect
<T>
to behave such as
<T: Any>
and to have a null value explicitly use
<T: Any?>
@Drew Hamilton@wcaokaze
d
Drew Hamilton
02/12/2020, 12:38 PM
I think either way you’d have to “just know” which one is the default because different people would have different intuitions. But IMO it makes sense because
Any?
is the lowest common denominator; the most generic available type in the JVM.
👍🏻 4
➕ 3
a
arekolek
02/12/2020, 12:38 PM
one example where
T : Any
makes sense:
Copy code
data class Optional<T : Any>(val value: T? = null)
interface Test {
fun test(): Optional<String?> // compilation error
}