2

So in Scala Some and None are the two sub-classes of Option.

To get an instance of Some, you can do both Some(x) or Option(x)

scala> val x = "Foo"
x: String = Foo

scala> Some(x)
res0: Some[String] = Some(Foo)

scala> Option(x)
res1: Option[String] = Some(Foo)

So it looks like there's not much difference. But of course if x is null, then they behave differently.

scala> val x:String = null
x: String = null

scala> Some(x)
res0: Some[String] = Some(null)

scala> Option(x)
res1: Option[String] = None

So it looks like, unless you want to preserve the null (for whatever reason), Option(x) is always preferable, because it's safer.

Even with literals, while we know for sure that Some("foo") cannot yield null, if later the string is extracted to a variable, you have to change it to Option to stay safe.

My question: Other than preserving null, is there any reason to use Some(x)?

Gabor Juhasz
  • 317
  • 2
  • 9

3 Answers3

3

There are a few different reasons for using it:

  1. It makes you realize what you're returning in a function. Let's say you have a function that might return a null value. You want to use an Option for this. You should write your code in such a way that you know whether you're returning a None or a Some because otherwise you might not know what's going on, and you're relying on the construction for Option to do that work for you, which may not do what you expect.

  2. When using a match statement, you need to have the difference to be able to choose between Some and a None because that's the whole point of using an Option.

Example:

val k: Option[Int] = someFunctionThatMightReturnInvalid()
k match {
    case Some(x) => println(x)
    case None => println("value is invalid")
}
childofsoong
  • 1,918
  • 16
  • 23
0

When you are doing a case match and you want to match that a value is actually Some(value) and not None

There are also many cases where you know for sure that a particular value won't be null and you would rather skip the null check that occurs in Option.apply

JoseM
  • 4,302
  • 2
  • 24
  • 35
0

To my understanding, null is not suggested to be directly used in Scala, which is why Option/Some/None was introduced. Some(null) is different from Option(null), but I can't see it is useful at all. So "Some" is only useful in pattern match in real life as previous answers say.

In addition, if you have a chance to learn Scalaz, which is a functional library for scala, it introduced "some", which behaves like Option in standard scala.

scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._

scala> 2.some
res18: Option[Int] = Some(2)

scala> some(2)
res19: Option[Int] = Some(2)
Binzi Cao
  • 1,075
  • 5
  • 14