Search code examples
kotlindefault-value

Pass no value to function with default parameters


I have this Kotlin function:

fun doSomething(user: User = defaultUser) {
  //do something
}

and I call it from another place:

val user: User? = getUser()
if (user == null) {
  doSomething()
} else {
  doSomething(user)
}

Is it possible to improve this code? I think this "if/else" is a little bit messy. Is possible to do something like this?

doSomething(user ?: NoValue)


Solution

  • You can cut it down to user?.run(::doSomething) ?: doSomething() (if doSomething doesn't return null) but I don't know why you'd want to!

    Honestly the if/else reads nice to me, stick it on one line without the braces and it's nice and compact. Unfortunately I don't think you can conditionally add parameters into a function call (and handling default parameters can get unnwieldy when you have a few).

    I agree with @benjiii, it might be better to have a nullable parameter and handle the default internally, if you don't need to use null as a legit value