SHARE
TWEET

Untitled

a guest Nov 30th, 2010 48 Never
  1. scala> import scala.util.control.Exception.catching
  2. import scala.util.control.Exception.catching
  3.  
  4. scala> def ?[T](block: => T): Option[T] = catching(classOf[NullPointerException]) opt block match {
  5.      | case Some(t) => if (t == null) None else Some(t); case _=> None }
  6. $qmark: [T](block: => T)Option[T]
  7.  
  8. scala> def lastmethodcall: String = null
  9. lastmethodcall: String
  10.  
  11. scala> def npe: String = {val s: String = null; s.toString}
  12. npe: String
  13.  
  14. scala> ?[String](npe)
  15. res27: Option[String] = None
  16.  
  17. scala> ?[String](lastmethodcall)  
  18. res28: Option[String] = None
  19.  
  20. scala> def yay="foo"
  21. yay: java.lang.String
  22.  
  23. scala> ?[String](yay)
  24. res29: Option[String] = Some(foo)
RAW Paste Data
Top