Kotlin documentation makes no mention on whether p...
# getting-started
k
Kotlin documentation makes no mention on whether parameter default values have to be constant or not and there's no equivalent in java to compare to. This appears to work:
Copy code
var defaultValue = 4
fun foo(number: Int = defaultValue) { /*something*/ }
even when I change the var, it appears to call the function with the new value. Is there any pitfalls of doing this that I'm unaware of or is it perfectly fine?
s
Seems there is a brief mention in the spec:
default argument expressions which are used (i.e., for which the call-site does not provide explicit arguments) are reevaluated at every such call-site. Default argument expressions which are not used (i.e., for which the call-site provides explicit arguments) are not evaluated at such call-sites.
https://github.com/Kotlin/kotlin-spec/blob/release/docs/src/md/kotlin.core/expressions.md
👍 1
k
Sounds like it should work then and it's definitely cleaner than overloads or ifs achieving the same result. At least its trivial to switch to those if it does misbehave down the line so I'll keep in the code for now.
👍 1
c
They don't have to be constant, but maintaining code where they are not immutable will not be fun.
plus one 3
e
Copy code
fun foo(number: Int = defaultValue)
is similar to writing
Copy code
fun foo() = foo(number = defaultValue)
fun foo(number: Int)
(there's some magic going on behind the scenes so that there's only one function (unless
@JvmOverloads
) but that's conceptually what happens)