Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a value from an option inside an option in Scala

Tags:

scala

slick

Given the following:

val x = Some(Some(1))

What would be the cleanest way to get the 1 (or -1 if the one did not exist)?

I'm creating an object instance from a tuple returned from a database query. One of the values in the tuple looks like this, so I would like a nice short 'one liner' to just get the value or set a parameter to -1.

like image 750
Jack Avatar asked Jan 17 '13 15:01

Jack


2 Answers

x.flatten is what you are looking for. Here it will give you Some(1). If you really want to get -1 for the case where "the one did not exist", just do x.flatten.getOrElse(-1):

scala> Some(Some(1)).flatten.getOrElse(-1)
res1: Int = 1
scala> Some(None).flatten.getOrElse(-1)
res2: Int = -1
scala> None.flatten.getOrElse(-1)
res3: Int = -1
like image 93
Régis Jean-Gilles Avatar answered Nov 09 '22 06:11

Régis Jean-Gilles


for-comprehensions are often a very readable way to use these kinds of nested structures:

  val x = Some(Some(1))
  val result = for {
    firstLevel <- x
    secondLevel <- firstLevel
  } yield {
    // We've got an int, now transform it!
    (secondLevel * 100).toString
  }

The result is an Option[String], and the transformation only happens when you have two Some(s).

You can also use pattern matching:

  val result2 = for {
    Some(v) <- x
  } yield {
    // We've got a int, now transform it!
    (v * 100).toString
  }
like image 30
James Moore Avatar answered Nov 09 '22 06:11

James Moore