0

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 ?

dbc
  • 104,963
  • 20
  • 228
  • 340
Hassan Syed
  • 20,075
  • 11
  • 87
  • 171
  • By the way, it is generally considered better to use camelCase for Scala identifiers than underscores. – Robin Green Nov 16 '13 at 12:01
  • 4
    If you want to have a type where you either have an empty sequence, or a non-empty sequence... why don't you just use `Seq`, instead of `Option[Seq]`? What does this give you, except reduced type safety, which is bad? – Robin Green Nov 16 '13 at 12:03
  • 1
    It would be nice if you could provide the code as an encapsulated method so that people can see all the corresponding types. makes it easier (at least for me:P) to read. – Stefan Kunze Nov 16 '13 at 12:05
  • 1
    Scalaz approach which encodes that you have performed this transformation (and thus your following code does not need to check again and again): `val quote = q.toNel` (`: Option[NonEmptyList[T]]`). – Debilski Nov 16 '13 at 15:28

2 Answers2

2
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
flavian
  • 28,161
  • 11
  • 65
  • 105
2

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) }
Knut Arne Vedaa
  • 15,372
  • 11
  • 48
  • 59