Hassan Syed
Hassan Syed

Reputation: 20485

Scala Sugar for Options of Seq

I need to map a sequence, and if empty consider it a None rather than a empty sequence. So :

val quote_ =
quote_inner_element.map( q=> {
  val quote_link_regex(quote_link_id) = q.attr("href")
  Quote(quote_link_id.toInt)
})
val quote = if(quote_.isEmpty) None else Some(quote_)

I hate having to define two variables. If I do

val quote = Option(
quote_inner_element.map( q=> {
  val quote_link_regex(quote_link_id) = q.attr("href")
  Quote(quote_link_id.toInt)
}))

Since I get tons of Some(Seq()). What's the sugar, sugar daddies ?

Upvotes: 0

Views: 3576

Answers (2)

Knut Arne Vedaa
Knut Arne Vedaa

Reputation: 15742

You can avoid creating two top-level vals in several ways:

Using an inner val:

val quote = {
  val quote = fooQuote map(q => myFunc(q))
  if (quote.isEmpty) None else Some(quote)
}

Note that even if the val names are identical, they don't refer to the same value; the inner one shadows the outer.

Using a match expresssion:

val quote = fooQuote map(q => myFunc(q)) match { case q => if (q.isEmpty) None else Some(q) }

Upvotes: 2

flavian
flavian

Reputation: 28511

implicit class SeqAugment[T](val s: Seq[T]) {
   final def toOption: Option[Seq[T]] = if (s.isEmpty) None else Some(s);
}
val s = Seq(1, 2, 3);
s.toOption

Upvotes: 2

Related Questions