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

Rich Errors wont’ support Elvis operator and most of all I think that here they’d be misused, forcing “UseDefault” to be an error.

Consider this scenario:

data class MyDC(val a: String = "defa", val b: String = "defa", val c: String = "defa")

It would be nice to keep the default values logic within the class having the opportunity to call it with only the known values, e.g.

fun getString(): String? {...}

val myclass = MyDC(getString() ?: default, getString() ?: default, getString() ?: default) 

whereas this would be equivalent to calling the function (contructor in this case) with only the (optional) parameters I’m aware of, deletegating the rest to default.
There’s currently no way to do this without changing the model or moving the defaults to the caller.