I learn Scala for some time and can’t clearly understand the usage of Option. It helps me to avoid null checks when I chain functions (according to docs). That’s clear for me 🙂
Next I see that Option can be kind of indicator for developer that null value is possible here and it must be handled. Is it true? If yes should I use Option whereever it’s possible? For example
class Racer {
val car = new Car()
}
I have Racer class and I’m sure that car field can’t be null (because it’s constant and get a value when I create Racer instance). No need for Option here.
class Racer {
var car = new Car()
}
Here I make it so that the car can change. And it’s possible for someone to assign null to car. Should I use Option here? If yes I notice that all my class fields are candidates for Option. And my code looks like this
class Racer {
var car: Option[Car] = None
var currentRace: Option[Race] = None
var team: Option[Team] = None
...
}
Does it look good? For me it seems kind of Option overusing.
def foo(): Result = {
if( something )
new Result()
else
null
}
I have a method which can return null. Should I return Option instead? Should I always do it if it’s possible for method to return null?
Any thoughts about it would be helpful. Thanks in advance!
My question is similiar to Why option but I think it’s not the same. It’s more about when, not why. 🙂
You should avoid
nullas much as possible in Scala. It really only exists for interoperability with Java. So, instead ofnull, useOptionwhenever it’s possible that a function or method can return “no value”, or when it’s logically valid for a member variable to have “no value”.With regard to your
Racerexample: Is aRacerreally valid if it doesn’t have acar,currentRaceandteam? If not, then you shouldn’t make those member variables options. Don’t just make them options because it’s theoretically possible to assign them tonull; do it only if logically you consider it a validRacerobject if any of those member variables has no value.In other words, it’s best to pretend as if
nulldoesn’t exist. The use ofnullin Scala code is a code smell.Note that
Optionhas many useful methods to work with.Also, if you want to program in the functional style, you should avoid mutable data as much as possible, which means: avoid the use of
var, usevalinstead, use immutable collections and make your own classes immutable as much as possible.