In Scala, the expressions you described mean that a method called ?
is invoked on an object called some
. Regularly, objects don't have a method called ?
. You can create your own implicit conversion to an object with a ?
method which checks for null
ness.
implicit def conversion(x: AnyRef) = new {
def ? = x ne null
}
The above will, in essence, convert any object on which you call the method ?
into the expression on the right hand side of the method conversion
(which does have the ?
method). For example, if you do this:
"".?
the compiler will detect that a String
object has no ?
method, and rewrite it into:
conversion("").?
Illustrated in an interpreter (note that you can omit .
when calling methods on objects):
scala> implicit def any2hm(x: AnyRef) = new {
| def ? = x ne null
| }
any2hm: (x: AnyRef)java.lang.Object{def ?: Boolean}
scala> val x: String = "!!"
x: String = "!!"
scala> x ?
res0: Boolean = true
scala> val y: String = null
y: String = null
scala> y ?
res1: Boolean = false
So you could write:
if (some ?) {
// ...
}
Or you could create an implicit conversion into an object with a ?
method which invokes the specified method on the object if the argument is not null
- do this:
scala> implicit def any2hm[T <: AnyRef](x: T) = new {
| def ?(f: T => Unit) = if (x ne null) f(x)
| }
any2hm: [T <: AnyRef](x: T)java.lang.Object{def ?(f: (T) => Unit): Unit}
scala> x ? { println }
!!
scala> y ? { println }
so that you could then write:
some ? { _.toString }
Building (recursively) on soc's answer, you can pattern match on x
in the examples above to refine what ?
does depending on the type of x
. :D