Can I change a when with check for null to a different approach?

Viewed 64

In Kotlin is there a more "Kotlin" way to do the following?

fun parse(inputSample: Sample): List<String> = 
   when {
     inputSample.foo != null -> parse(inputSample.foo)
     inputSample.bar != null -> parse(inputSample.bar)
     else -> emptyList()
  }

I suspect that check for null with when can be written differently in Kotlin

2 Answers

You can use scoping function to reduce "redundant" code:

fun parse(inputSample: Sample): List<String> = inputSample.run {
    when {
        foo != null -> parse(foo)
        bar != null -> parse(bar)
        else -> emptyList()
    }
}

Or combining with elvis operator (note this assumes foo and bar are of same type):

fun parse(inputSample : Sample) : List<String> = inputSample.run {
    (foo ?: bar)?.let { parse(it) } ?: emptyList()
}

I'm not sure if it is a more Kotlin way, but you can also do the following

fun parse(inputSample: Sample): List<String> = 
      inputSample.foo?.let { parse(it) } ?: inputSample.bar?.let {parse(it) } ?: emptyList()
Related