Skip to content

Instantly share code, notes, and snippets.

@zhaohangbo
Created November 21, 2016 04:31
Show Gist options
  • Save zhaohangbo/ba73b4688784fcf963dd2e526d992e78 to your computer and use it in GitHub Desktop.
Save zhaohangbo/ba73b4688784fcf963dd2e526d992e78 to your computer and use it in GitHub Desktop.
Use Option(x) instead of Some(x) to avoid Some(null)
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