0

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)

Héctor
  • 24,444
  • 35
  • 132
  • 243

3 Answers3

4

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

cactustictacs
  • 17,935
  • 2
  • 14
  • 25
1

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())
benjiii
  • 413
  • 3
  • 9
1

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())
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74