Hi, is there optional parameters in Kotlin ? the d...
# getting-started
x
Hi, is there optional parameters in Kotlin ? the doc have no hints about that. I've marked the param
info
as
nullable
, why still got error?
v
You also have to give it a default value to have it optional, so add
= null
after the question mark
x
yes it works! but still feel confused about that. If I marked as nullable,then the default value should be
null
, why I have to add the default value explicitly. 😅
v
No, if it is nullable it means someone invoking it can specify
null
, but the invoker still has to decide what he wants to give. If you want the parameter to be optional in terms of being able to not specify it, you have to define a default value which can be
null
but also any other valid value.
✅ 1
Actually it might also be better to not use a nullable type here, but instead use an empty map as default value.
k
Nullability and existence of a parameter are two separate concepts. Consider an overload:
Copy code
fun foo(name: String, info: May<Int, Map<String, Any>>?) { ... }
fun foo(name: String) { ... }
Now you can call
foo("bar", null)
and
foo("bar")
and those are different things. The first is a null parameter, the second is no parameter.
🙌 1
v
Same with the default argument though, so what does that add except for more verbosity?