Tuesday, September 22, 2015

Four ways to retrieve Scala Option value

Suppose you have the Scala value assignment below, and wish to append " World", but only if the value is not None (from Option[]).

val s = Some("Hello")

There are four different Option[] idioms to accomplish this:
  1. The Java-like way

    if (s.isDefined) s.get + " World" else "No hello"
     
  2. The Pattern Matching way

    s match { case Some(s) => s + " World"; case _ => "No hello" }
     
  3. The Classic Scala way

    s.map(_ + " World").getOrElse("No hello")
     
  4. The Scala 2.10 way

    s.fold("No hello")(_ + " World")

No comments: