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. :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…