8

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?

3
  • 1
    Using Any as the type for your methods (or method parameters) brings you to a real hell (you lose all the power the type system offers you). That said, the most idiomatic way to use an Option instance is to treat it as a collection or monad and use map, flatMap, filter, or foreach. Commented Apr 7, 2016 at 7:00
  • oracle.com/technetwork/articles/java/… Scroll down to "Do something if Value is present" ... Commented Apr 7, 2016 at 7:12
  • 2
    Scala already has fold to do this: test.fold(addError("not found"))(builder ++= _) Commented Apr 7, 2016 at 7:19

2 Answers 2

17

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")
  }
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for that. The map method also looks useful used in that manner. With the fold method can't I write the fold(...)(...) as fold \n (...) \n (...)? In the sense put a new line after the fold and after each of the brackets for readability. My IDE shows as an error.
try with curly brackets {}: Some(2).fold { println("error") } { value => println(s"Success: $value") }
1

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! ; )

3 Comments

You're missing the OP's point. I think he understands that. But he wants to do something when the Option is None, which is not unreasonable. Map etc allow you do do something when the Option is some (and do nothing when it/s None) but if you do have something specific to do when it is None (for instance, display an error message), that's not as well supported.
my answer was based on his: "I must be doing something wrong. Most likely, my understanding of how to use Options is flawed." comment
Still doesn't answer his actual question, which is about handling the None case (see the subject line and the question at the end)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.