Héctor
Héctor

Reputation: 26034

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)

Upvotes: 0

Views: 784

Answers (3)

Adam Millerchip
Adam Millerchip

Reputation: 23091

I agree with cactustictacs, just putting it on one line is clear and simple. However, if you use it often and it's bothering you, it's easy enough to wrap it in a function without the default parameter:

fun doSomethingSensibly(user: User?) =
    if (user == null)
        doSomething()
    else
        doSomething(user)

Which can be used as:

doSomethingSensibly(getUser())

Upvotes: 1

benjiii
benjiii

Reputation: 553

You could do something like this:

getUser()?.let { // user is not null
  doSomething(it)
} ?: run { // user is null here
  doSomething()
}

(cf: Swift 'if let' statement equivalent in Kotlin)

I don't think you could do something shorter without making the code hard to understand Edit 2: Actually you can, see the comment

Edit: I would personally handle the nullable variable inside the function like this:

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

so you can use the function like this:

doSomething(getUser())

Upvotes: 1

cactustictacs
cactustictacs

Reputation: 19524

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

Upvotes: 4

Related Questions