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?
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.
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.
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.
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.
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) }
The canonical guide to Option wrangling is by Tony Morris.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With