Created
November 21, 2016 04:31
-
-
Save zhaohangbo/ba73b4688784fcf963dd2e526d992e78 to your computer and use it in GitHub Desktop.
Use Option(x) instead of Some(x) to avoid Some(null)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object NullNotNone { | |
def main(args: Array[String]) { | |
test_func match { | |
case None => println("null is not none") | |
case Some(x) => println("so easy to be wrong") | |
} | |
} | |
def test_func: Option[java.lang.Double] = Some(null) | |
} | |
// Option源代码(Source Code of Option) | |
object Option { | |
import scala.language.implicitConversions | |
/** An implicit conversion that converts an option to an iterable value | |
*/ | |
implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList | |
/** An Option factory which creates Some(x) if the argument is not null, | |
* and None if it is null. | |
* | |
* @param x the value | |
* @return Some(value) if value != null, None if value == null | |
*/ | |
def apply[A](x: A): Option[A] = if (x == null) None else Some(x) | |
/** An Option factory which returns `None` in a manner consistent with | |
* the collections hierarchy. | |
*/ | |
def empty[A] : Option[A] = None | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment