Where is the method that boxes an AnyRef into an Option?
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 opt开发者_运维知识库ion
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.
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
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.
精彩评论