Mr. Adobo
Mr. Adobo

Reputation: 835

How do I return a None in scala?

I've been learning Scala recently and one of the things I've seen most is talk about how you shouldn't use null but instead use None. I've had to resort to using null some times because I don't understand how None works exactly.

My biggest problem is when I have methods which return an object say:

def func: SomeObjType = {
if(something)
    new SomeObjType
else
    null or None

If I return null, it works perfectly well but whenever I try to return None it doesn't work.

What am I doing wrong?

Upvotes: 1

Views: 2518

Answers (2)

SG324
SG324

Reputation: 1

None, as you can see in the scaladocs here, is an extension of Option. It only checks out if your return type is expected to be an Option.

You can alter your code as Marth suggests, but in practice, Option makes for rather ugly code if it is used constantly.

If you are dealing with Lists, returning a Nil would be quite suitable.

I personally just return Nothing, just because it sounds cool, and because its autoinheritence of every class (including SomeObjType) makes it simple to deal with.

The following article is a very useful piece about these absentee-types in Scala:

A Post About Nothing, by Matt Malone

And really, with all these alternatives, there's little appeal for a lower-case null. It even pales in the face of the aesthetically-pleasing Null. Quirks aside, null and Null can be used more or less interchangeably.

Upvotes: -3

Marth
Marth

Reputation: 24832

def func : Option[SomeObjType] = {
  if (cond)
    Some(new SomeObjType)
  else 
    None
}

Upvotes: 8

Related Questions