Search code examples
scalafunctional-programmingscala-option

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 ?


Solution

  • 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) }