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:
- The Java-like way
if (s.isDefined) s.get + " World" else "No hello"
- The Pattern Matching way
s match { case Some(s) => s + " World"; case _ => "No hello" }
- The Classic Scala way
s.map(_ + " World").getOrElse("No hello")
- The Scala 2.10 way
s.fold("No hello")(_ + " World")
No comments:
Post a Comment