Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for..else for Option types in Scala?

Suppose I have two Options and, if both are Some, execute one code path, and if note, execute another. I'd like to do something like

for (x <- xMaybe; y <- yMaybe) {
  // do something
}
else {
  // either x or y were None, handle this
}

Outside of if statements or pattern matching (which might not scale if I had more than two options), is there a better way of handling this?

like image 909
davetron5000 Avatar asked Jul 31 '11 17:07

davetron5000


People also ask

What is option type in scala?

Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value.

What is getOrElse in scala?

As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.

What is some () in scala?

Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some.

What is Option string?

The STRING option in GET and PUT statements transmits data between main storage locations rather than between the main and a data set. DBCS data items cannot be used with the STRING option.


2 Answers

Very close to your syntax proposal by using yield to wrap the for output in an Option:

val result = { 
  for (x <- xMaybe; y <- yMaybe) yield {
    // do something
  }
} getOrElse {
  // either x or y were None, handle this
}

The getOrElse block is executed only if one or both options are None.

like image 193
paradigmatic Avatar answered Oct 25 '22 02:10

paradigmatic


You could pattern match both Options at the same time:

(xMaybe, yMaybe) match {
  case (Some(x), Some(y)) => "x and y are there"
  case _ => "x and/or y were None"
}
like image 25
kassens Avatar answered Oct 25 '22 02:10

kassens