I am confused by Kotlin generics. My understanding...
# getting-started
v
I am confused by Kotlin generics. My understanding was that if I declare
T
generic argument it implicitely uses
Any?
as the upper boundary. Otherwise what would
T : Any
do? But then it is not letting me to set
T
to
null
.
Copy code
interface Form<T> {
    
}

abstract class SpecificForm<T> {
    
    private var bean: T = null // does not compile
}
why do I have to declare the
bean
as
T?
when
T
already is includes nullable types?
j
Because
T
could be a non-null type. It's not guaranteed to be nullable.
1
v
here is a closer example:
Copy code
interface Form<T> {

    fun getBean(): T
}

class GenericForm<T : Any?> : Form<T> {

    override fun getBean(): T {
        return null
    }
}
why can’t i return
null
here? the T is clearly declared as nullable
my problem is that if I declare
getBean()
to return
T?
then non of the interface implementations can return non-nullable
T
😞
j
No it's not declared as nullable.
: Any?
doesnt add any bounds to
T
So someone could pass a non-nullable
T
still
👆🏼 1
v
i understand.. they would build
GenericForm
as having
String
and then
getBean
would return
null
which does not conform to
T
j
my problem is that if I declare
getBean()
to return
T?
then non of the interface implementations can return non-nullable
T
Subclasses can override a function with a nullable return type to narrow the scope to return a non-null.
v
cool, that does help! can’t override a method parameter that way though
fun setBean(bean: T?)
cannot be overridden as
fun setBean(bean: T)
j
Correct
v
thanks all gratitude thank you
👍🏼 1