https://kotlinlang.org logo
Title
a

Alexander Maryanovsky

02/19/2022, 1:12 PM
Given a function with a default argument, is there a way to call it with its default argument? I want to write a wrapper function for it while preserving the default argument value. Basically this, but without the if
fun foo(arg1: Int, arg2: Int = 42){ ... }

fun wrapper(arg1: Int, arg2: Int? = null){
    if (arg2 == null)
        foo(arg1)
    else
        foo(arg1, arg2)
}
s

Sam

02/19/2022, 1:15 PM
Possible with reflection, using
callBy
, but I wouldn't recommend that as a solution here
Do you expect people to pass
null
, or is that just a placeholder? You could use overloads, if you just need a 1-arg version and a 2-arg version:
fun wrapper(arg1: Int) = foo(arg1)
fun wrapper(arg1: Int, arg2: Int) = foo(arg1, arg2)
e

ephemient

02/19/2022, 1:17 PM
a

Alexander Maryanovsky

02/19/2022, 1:19 PM
Thanks