A new feature for default arguments

Hello!

Image a function that has a default argument.

Is there a way to call this function with a certain argument if a condition is met, else use the default argument?

Here’s some code:

fun foo(arg: String = "Default value”) { … }

fun main() {

foo(

  arg = if (...) "My value" else default() // I'm inventing here a default function (a possible new feature, which of course can also be made in other ways) which calls the function with its default argument!

)

}

Here, the default argument is quite straight forward, but in more complex scenarios, it may involve more computations, which I’d like not to repeat when calling the function using the else case above (and thus use this new feature I’m mentioning)!

Thank you for your attention and support! Kotlin is awesome

Unfortunately, I believe the only way is:

if (...) foo("My value") else foo()
1 Like

Rich Errors may help here. You’d be able to do:

error object UseDefault
fun foo(arg: String | UseDefault = UseDefault) {
  val arg = arg ?: "Default value"
  ...
}

You can already do this with null, but it can be confusing for your callers. Having a special error object for it makes the intent clear

1 Like

I don’t think so. I expect that Rich Errors will only be allowed as return types. And this video also makes me sure if it: https://youtu.be/IUrA3mDSWZQ?si=S7BiM8rFSB7BMbp4&t=1688

This timestamp shows otherwise

1 Like