Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reproduce Scala's behavior for ==?

Tags:

null

scala

equals

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?

like image 371
Jean-Philippe Pellet Avatar asked Jan 21 '23 15:01

Jean-Philippe Pellet


2 Answers

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

Update

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
like image 115
tenshi Avatar answered Jan 28 '23 12:01

tenshi


"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 :)

like image 36
Adam Rabung Avatar answered Jan 28 '23 12:01

Adam Rabung