Having the following simple extension in scope:
(for Scala 2.10):
implicit class AnyExtensions[A] ( val x : A ) extends AnyVal {
def asSatisfying(p: A => Boolean): Option[A] =
if (p(x)) Some(x) else None
}
(for Scala 2.9):
implicit def anyExtensions[A] (x : A) = new {
def asSatisfying(p: A => Boolean): Option[A] =
if (p(x)) Some(x) else None
}
you'll be able to rewrite your code as follows:
mySeq
.asSatisfying{_.nonEmpty}
.map{
_.map{elmt =>
// do stuff
}
}
.getOrElse{
// some other stuff
}
In my practice this extension turned out to be applicable in a lot of cases and very useful. It excels in situations when you realize you need an if
statement in a middle of an expression, which without this extension would have required you to introduce a temporary variable. Here's an example:
List(1, 2, 3).mkString(", ").asSatisfying{_.nonEmpty}.getOrElse("Empty list")
It will result in a String
1, 2, 3
and would have resulted in a String
Empty list
if the list was empty.
if (seq.isEmpty) ... else seq.map(...)
? – Staurolite