Skip to content

Instantly share code, notes, and snippets.

@chirino
Created August 6, 2010 13:50
Show Gist options
  • Save chirino/511342 to your computer and use it in GitHub Desktop.
Save chirino/511342 to your computer and use it in GitHub Desktop.
final class RichAnyRef[T <:AnyRef](val value: T) extends Proxy {
def self: Any = value
def ? : Option[T] = if( value==null ) None else Some(value)
def ?[R] ( func: (T=>R) ) : Option[R] = if( value==null ) None else Some(func(value))
}
implicit def RichAnyRefWrapper[T <:AnyRef](x: T) = new RichAnyRef(x)
final class RichOption[T](val value: Option[T]) extends Proxy {
def self: Any = value
def | (other:T): T = value.getOrElse(other)
}
implicit def RichOptionWrapper[T](x: Option[T]) = new RichOption(x)
var x = "hello"
x.?.|("not set")
x.?( _.length )
x = null
x.?.|("not set")
x.?( _.length )
@chirino
Copy link
Author

chirino commented Aug 6, 2010

scala> var x = "Hello"
x: java.lang.String = Hello

scala> x.?
res0: Option[java.lang.String] = Some(Hello)

scala> x = null
x: java.lang.String = null

scala> x ?
res2: Option[java.lang.String] = None

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment