Where is the method that boxes an AnyRef into an Option?

1.1k views Asked by At

In this blogpost by James Iry, he writes:

Plus, Scala has an "option" method that promotes a value to either Some(value) or None depending on whether it's null or not ...

I can't seem to find this option method anywhere in the scaladoc.

Iulian Dragos's gdata client project contains a method that is probably what James was referring to.

def option[A <: AnyRef](a: A): Option[A] =
  if (a eq null) None else Some(a)

Please point out where can I find this method in the scaladoc.

P.S. I have a method that looks like this:

def permutations(s: String): List[String] = ...

I'm in 2 minds as to whether I should change it to:

def permutations(s: Option[String]): List[String] = ...

since the client can invoke it with null. Currently in the first instance, I expect a String parameter & I box it manually using the option method mentioned previously.

2

There are 2 answers

0
Wilfred Springer On BEST ANSWER

You can simply use the apply factory method on its companion object:

scala> Option.apply("Test")                
res51: Option[java.lang.String] = Some(Test)

scala> Option.apply(null)  
res52: Option[Null] = None

... or the shorter version:

scala> Option("Test")  
res49: Option[java.lang.String] = Some(Test)

scala> Option(null)
res50: Option[Null] = None
4
sourcedelica On

The Scaladoc page is http://www.scala-lang.org/api/current/scala/Option$.html.

To navigate to it from the main Option page click on the big "C" in the circle next to the class name at the top of the page. That toggles between the class and the companion. You can also navigate to the companion by clicking the "O" in the left nav to the left of the class name.