Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Option - Getting rid of if (opt.isDefined) {}

My code is becoming littered with the following code pattern:

val opt = somethingReturningAnOpt if (opt.isDefinedAt) {     val actualThingIWant = opt.get } 

Is there some way to simplify this? (it seems needlessly complex and a code smell). Ideally it would be something like:

if (Some(actualThingIWant) = somethingReturningAnOpt) {    doSomethingWith(actualThingIWant) } 

Is anything like that possible?

like image 420
laurencer Avatar asked Dec 08 '11 06:12

laurencer


People also ask

What is isDefined in Scala?

Definition Classes IterableOps.  final def isDefined: Boolean. Returns true if the option is an instance of scala. Some, false otherwise. Returns true if the option is an instance of scala.Some, false otherwise.

What is option () in Scala?

The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.

What is an option t?

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.


2 Answers

Maybe something like this:

somethingReturningAnOpt match {   case Some(actualThingIWant) => doSomethingWith(actualThingIWant)   case None => } 

or as pst suggests:

somethingReturningAnOpt.foreach { actualThingIWant =>   doSomethingWith(actualThingIWant) }  // or...  for (actualThingIWant <- somethingReturningAnOpt) {   doSomethingWith(actualThingIWant) } 
like image 82
Rogach Avatar answered Sep 20 '22 18:09

Rogach


The canonical guide to Option wrangling is by Tony Morris.

like image 40
Duncan McGregor Avatar answered Sep 21 '22 18:09

Duncan McGregor