How do you usually use to replace if-without-else in Scala in functional way?
For example, like this typical pattern in imperative style:
var list = List("a", "b", "c")
if (flag) { // flag is boolean variable
// do something inside if flag is true
list = "x" :: list
}
// if flag is false, nothing happened
I'm thinking like this to make it functional:
val tempList = List("a", "b", "c")
val list = if (flag) "x" :: tempList else tempList
Could there be a better way without using intermediary variable?
So anyone can share how do you eliminate if-without-else in scala?
It's generally better to avoid cluttering your namespace with temporary variables. So something like this would be better:
val list = {
val temp = List("a", "b", "c")
if (flag) "x" :: temp else temp
}
or
val list = List("a", "b", "c") match {
case x if flag => "x" :: x
case x => x
}
If you find yourself doing this a lot and performance is not a big concern, it might be handy to define an extension method. I have one in my personal library that looks like this:
implicit class AnythingCanPickFn[A](private val underlying: A) extends AnyVal {
/** Transforms self according to `f` for those values where `p` is true. */
@inline def pickFn(p: A => Boolean)(f: A => A) =
if (p(underlying)) f(underlying) else underlying
}
You'd use this one like so:
List("a", "b", "c").pickFn(_ => flag){ "x" :: _ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With