Hello, is there any reason it is not possible to access the default value of a parameter in a functi...
l
Hello, is there any reason it is not possible to access the default value of a parameter in a function?
p
What is your use case? Default value is an expression in function body (thus can have side effect) that is evaluated only if not specified at caller side
In case of possibility to take its value in function body will break contract. Caller is expected to compute default expression only if value for it is not specified.
Copy code
fun test1(v: Int = 1.also { println("!") }) {
    }

    fun test() {
        test1() // will print !
        test1(2) // will not print !
    }
What will be good is to have possibility to specify in caller side that value parameter must be taken as default value
Copy code
fun test1(x: Int = 12345)

fun test(y: Boolean) {
  test1(if (y) 10 else default) // will be good to have this
}
k
What do you mean by "that is evaluated at most ones"? It seems to be evaluated every time it's called, not just once.
p
I mean that default value is evaluated only if not specified directly. Edited message to clarify this.
👍 1
Also it will be good to have such possibility:
Copy code
fun test1(x: Int = 123)

fun test2(x: Int = test1::x::default) // something like this
🚫 1
d
Another reason is that default values can depend on the values of other arguments, for example:
Copy code
fun foo(
    w: Int,
    x: Int = w + 1,
    y: Int = x + 1,
    z: Int = x + y
) {
    println("w: $w, x: $x, y: $y, z: $z")
}
This would make designing a general API to retrieve a default value rather difficult.
l
In my specific case, I'd like to compare the actual value to the default one, and my default values have no side effects, most of them are number literals.
p
In general case it can have side effect. For your case one of solutions is to define constants and specify defaults with them and in the function body check actual value parameters with constant values.
2
l
I know, but it's a lot more verbose, and gives an indirection when you want to see the actual default value. I don't like it.