Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace if-without-else in Scala

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?

like image 546
null Avatar asked Feb 01 '15 14:02

null


1 Answers

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" :: _ }
like image 164
Rex Kerr Avatar answered Oct 02 '22 16:10

Rex Kerr