goo
goo

Reputation: 2280

Scala: "getOrElse" in a block

I'm new to Scala & everyone tells that it's bad to use something like if myFoo.get is null then when myFoo is wrapped in an Option (Such as Option[myFoo]) in Scala

I keep coming across getOrElse but all the answers referring to getOrElse just confuses me even more even though it sounds so simple ("getOrElse").


Here's what I'm trying to do. If myFoo is null then do something but if it's not then do somethingElse.

Could someone please explain it in the most simplest way possible for me? Doesn't have to be a long answer but I'd appreciate all the help I can get.

Upvotes: 2

Views: 5430

Answers (2)

senia
senia

Reputation: 38045

It looks like you have not an Option, but some value that could be null:

If myFoo is null

In this case you have to wrap it with Option: Option(myFoo).

val result = Option(myFoo) match {
  case Some(value) =>
    // something
    // you could use `value` here
  case None =>
    // something else
}

Option(myFoo) wraps myFoo with Option: if it's null you'll get None otherwise you'll get Some(myFoo).

See this article: scala.Option Cheat Sheet for methods to work with Option.

Also take a look at this answer.

Note that if myFoo is an Option, than you don't need to wrap it: replace Option(myFoo) match with myFoo match.

Also you should note that get on empty Option (on None) throws an exception instead of returning null:

if myFoo.get is null then

You'll get an exception, not null. You should never use get.

Upvotes: 7

wheaties
wheaties

Reputation: 35970

Option can be two types: Some and None. None denotes the abscence of some contained value while Some denotes that it has a value. Think of Option as a list of 1 element. So when you do a getOrElse, what you're really saying is give me that value or if empty, give me this other value.

Upvotes: 2

Related Questions