https://kotlinlang.org logo
g

gabrielfv

08/15/2017, 8:02 PM
what you guys think about nullable parameters defaulting to null?
fun foo(bar: Int?)
can be called like
foo()
, instead of having to write
fun foo(bar: Int? = null)
. I see people comonly reading the
?
as sort of "opitional" in this context, and I don't see the point of calling
foo(null)
, though makes some sense when
Copy code
val a: Int? = mayReturnInt()
foo(a)
which is also a common scenario
👍 1
10
u

umar

08/15/2017, 9:36 PM
There are few cases you really need nullable types, so being explicit achieves two goals: you can see that here is default argument and it is null, and code will be consistent for nullable and nonnullable types.
☝️ 2
g

gabrielfv

08/15/2017, 9:40 PM
I see those cases. I see that there would be consistence between types given that when they have the
?
operator they could be
null
by default, and there'd be no other possibility for a default value, unlike 0 for
Int
or
""
for
String
.
Having types not null by default and depending on an attention raising operator like
?
makes it very clear that a value can be null. That's it's role after all.
It also doesn't break consistency with non-null parameters, since
fun foo(a: Int? = 0)
can accept
foo(null)
, with
a
actually being
null
and
foo()
with
a
being
0
.
The other side, the scenario where
fun foo(bar: Int)
would not be passive of being called
foo()
and would break is not a different behavior, but could be due to the fact that
bar
could not be null and therefore there is no way to infer anything.
b

benleggiero

08/16/2017, 1:53 AM
Too confusing. Looks like
?
means "optional parameter", not "nullable and optional". I can imagine newcomers thinking that Kotlin only allows omitted optional parameters to be null and not bothering to discover the
=
syntax
This would also break any APIs where the designer wanted the developer to be explicit about whether something's null
g

gabrielfv

08/16/2017, 4:50 AM
I don't see what you mean in this last message, @benleggiero
APIs that wanted the user to call a method like
foo(null)
explicitly? Is there any example?
u

umar

08/16/2017, 6:07 AM
Can you get with use case, where you need so many `nullable`s, and their default must be
null
?
3 Views