May be stupid but a junior dev here :smile: Is th...
# android-architecture
o
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
In the second one,
T
can be a nullable type. In the first one, it can’t be.
👍 1
w
Yep. In other words,
<T>
means
<T : Any?>
👍 1
o
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
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
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
}
It's a constraint https://kotlinlang.org/docs/tutorials/kotlin-for-py/generics.html#constraints so it makes sense that without no constraints it is the most general type
👍 1
o
Got it, that makes sense thank you!
👍🏻 1