Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala and Java Options do if present if not do something else construct

Options in scala and java are something that I am struggling to understand and work with. I understand its there in order to eliminate 'null' handling hell. Frankly, I think its introducing another kind of hell!

The way I deal with nulls in java is to do something like:

String test = null;
if(test==null) // do something
else  // do something else

This sort of decision is what I am seeking to do when I switch to Options.

But there is no method in the Option class in both scala and java to say, if null do something, else do something else.

There is a way to default the value in case of subject being null, such as

//in scala
test.getOrElse("defaulted")

I was wondering why there cant be methods such as the implicit class I have written to 'pimp up' a Scala option

object Definitions{
  implicit class OptionExtensions[$Data](option: Option[$Data]){
    def perform (found: ($Data)=>Any, notFound: ()=>Any): Any={
      option match{
        case Some(data)=> found(data)
        case None=> notFound()
      }
    }
  }
}

Please ignore the badly named method. But with this now written, I could supposedly use an option like this:

import Definitions._

val test : Option[String] = None

var builder =new StringBuilder


test.perform(builder ++= _, ()=>addError("not found"))
//or
println(test.perform(_.reverse, ()=>{"something else"}))

def addError(error:String)={
  println(error)
}

Instead I am forced to write match and case for handling anything to do with Options. I must be doing something wrong. Most likely, my understanding of how to use Options is flawed. The above way of handling is not in the Option class by default because of a reason. Now what could that reason be?

like image 994
sethu Avatar asked Apr 07 '16 06:04

sethu


People also ask

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.

How do you use some and options in Scala?

An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.

Which are the forms of the option class in Scala?

filter – Returns the Option if the Option's value is Some and the supplied function returns true. filterNot – Returns the Option if the Option's value is Some and the supplied function returns false. exists – Returns true if the Option is set and the supplied function returns true.

Why do we use some in Scala?

Some of the methods available for some class in scala are as follows; nonEmpty: This method also returnBoolean. It will return true of the object is not empty else false. isEmpty: This method is used to check the object id empty or not, it returns a Boolean value.


2 Answers

In scala there are several ways to achieve that:

  • optValue.map(successFunction).getOrElse(errorFunction)
  • optValue.fold(errorFunction)(successFunction)

probably what you want is the second, fold.

In java there's a .map, not sure if there's a .fold, you need to have a look at the docs

EDIT: As you asked to have newlines in fold, try with brackets:

Some(2).fold
  {
    println("error")
  }
  {
    value =>
      println(s"Success: $value")
  }
like image 123
pedrorijo91 Avatar answered Oct 12 '22 10:10

pedrorijo91


I think what you're missing is the reason why you need Options.

The idea behind Options (and Optionals in Java), is that you (the developer) can now state that a value may or may not be present, on the type level.

Take a second to think about that. How would you do that with a variable that could just be null?

...

It's a problem, right?

  • you don't know if it would ever be null when you get to read the value
  • you must always check if it is null with such a variable, if you want your code to be safe.

But, now, with Options / Optionals, you and some other developers who work with your code are now told by the compiler that they must check the possibility that this variable will be null (or not!).

If we now take this a step further, imagine if you write all your code in a way that any variable that might be null is an Option. Any variable that will never be null (will always have a value), is not! You get my point now, right?

If you write all your code like this, you will end up never accidentally relying on the presence of value that are not there, nor making unnecessary checks about whether the value was there, when it always is! ; )

like image 24
gsaslis Avatar answered Oct 12 '22 09:10

gsaslis