Skip to content

Instantly share code, notes, and snippets.

@chirino
Forked from rossabaker/gist:511426
Created August 6, 2010 14:57
Show Gist options
  • Save chirino/511432 to your computer and use it in GitHub Desktop.
Save chirino/511432 to your computer and use it in GitHub Desktop.
object Elvis {
private class ElvisNull extends RuntimeException
final class ElvisAny[T](val value: T) extends Proxy {
def self: Any = value
def ? : T = if( value==null ) throw new ElvisNull else value
def :| (func: =>T): T = {
try {
return func
} catch {
case e:ElvisNull=>
return value
}
}
// def ?[R] ( func: (T=>R) ) : Option[R] = if( value==null ) None else Some(func(value))
}
implicit def ElvisAnyWrapper[T](x: T) = new ElvisAny(x)
implicit def opt[T](func: => T): Option[T] = {
try {
return Some(func)
} catch {
case e:ElvisNull=>
return None
}
}
}
import Elvis._
var x = "hello"
"not set" :| x.?
0 :| x.?.length
x = null
"not set" :| x.?
0 :| x.?.length
// Implicitly convert to an Option
x.?.length.getOrElse(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment