https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Kaj Koivunen

01/18/2023, 2:24 PM
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

Sam

01/18/2023, 2:30 PM
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

Kaj Koivunen

01/18/2023, 2:33 PM
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

CLOVIS

01/18/2023, 3:36 PM
They don't have to be constant, but maintaining code where they are not immutable will not be fun.
plus one 3
e

ephemient

01/18/2023, 6:44 PM
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)
6 Views