In Programming in Scala, I can read that the ==
operator behaves as if it was defined like this:
final def == (that: Any): Boolean = if (null eq this) {null eq that} else {this equals that}
But there must actually be compiler magic to avoid null pointer exceptions, right? Is there any way for me to replicate this behavior with pure Scala; i.e., have an operator/method return one thing if the receiver is null and another one if it isn't? What I mean is an actual implementation of null eq this
.
I suppose I can write a "pimp" and then define the method on the wrapper class, but is there a more direct way to do this?
I don't think so. As far as I know there is no magic for nulls. (see Update)
I think the best you can do, is to wrap any object to option, so that you can use bunch of useful stuff from it:
implicit def toOption[T](target: T) = Option(target)
val q: String = null
val q1: String = "string"
println(q getOrElse "null") // prints: null
println(q1 getOrElse "null") // prints: string
I found this document:
http://www.scala-lang.org/api/2.7.7/scala/Null.html
According to it:
Class Null is - together with class Nothing - at the bottom of the Scala type hierarchy.
So even null
has methods inherited from AnyRef
like eq
, ==
, etc... And you also can use them:
val q: String = null
val q1: String = "string"
println(null eq q) // prints: true
println(null eq q1) // prints: false
"null" is the only instance of a trait called Null - so it's just a normal object, no magic to invoke ==
You should definitely check out Option and do everything you can to keep nulls out of your code :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With