-
-
Save chirino/511432 to your computer and use it in GitHub Desktop.
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 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