is it idiomatic to use `T?` like an optional of ty...
# getting-started
y
is it idiomatic to use
T?
like an optional of type
T
?
j
Yes, though I guess it depends on what you need to express.
T?
is meant to express "the nullable version of T, no matter whether T is already nullable or not". Note that an unconstrained T is already potentially nullable, depending on the type parameter that's actually passed in a specific usage of your generic declaration
k
As Joffrey Bion mention you'd have to constraint your type
T
to
T: Any
then you should be able to use
T?
as an "optional"
T
y
wait, is this true for a concrete
T
?
as in,
val foo: Foo?
is nullable, but
val foo: Foo
is not, correct?
👌 2
k
No for concrete types it's not same, the implicit nullability of the type is only true for generics
y
okay, phew.
j
Foo
is not nullable,
Foo?
is nullable. Both can be passed as
T
to a generic declaration if
T
is not constrained
👆 2
y
oh, yes. that also aligns with my understanding. thanks about that clarification. so, just making sure: say I’m making a Kotlin class, and I need an optional field (of a non-generic type, let’s say
Foo
), I should use a
Foo?
, correct?
👌 2