This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Option constructor, == or eq?

5 replies
ArtemGr
Joined: 2009-01-12,
User offline. Last seen 4 days 21 hours ago.

The current Option constructor uses "==" to test if the value is null.

E.g.
Option (value)
is equal to
if (value == null) Some (value) else None

I think that this can introduce undesired effects
(what if a badly written equals method doesn't know hot to handle null?)
and unnecessary performance penalty,
calling into a possibly large and complex equals method
while all we want is to check if the value is null.

I'd say it should be "if (value eq null) Some (value) else None",
unless I'm missing some nifty optimizations made in Scala 2.8
regarding comparison to null.

Colin Bullock
Joined: 2009-01-23,
User offline. Last seen 42 years 45 weeks ago.
Re: Option constructor, == or eq?
The implementation of == is guaranteed to be null-safe. From the spec (§12.1):

/** Semantic equality between values */
final def == (that: Any): Boolean =
  if (null eq this) null eq that else this equals that

- Colin
ArtemGr
Joined: 2009-01-12,
User offline. Last seen 4 days 21 hours ago.
Re: Option constructor, == or eq?

Colin Bullock gmail.com> writes:

>
> The implementation of == is guaranteed to be null-safe. From the spec
(§12.1):/** Semantic equality between values */ final def == (that: Any):
Boolean =   if (null eq this) null eq that else this equals that - Colin

So what?
It still calls "this equals that", which can be slow / unsafe, and isn't what we
need when checking for null.

Colin Bullock
Joined: 2009-01-23,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Option constructor, == or eq?
The AnyRef.equals() method is only called after checking (via eq, reference equality) that neither object is null. In the case of Option.apply(), the second argument is most assuredly null, ergo, value.equals() ever called.

- Colin
ijuma
Joined: 2008-08-20,
User offline. Last seen 22 weeks 2 days ago.
Re: Option constructor, == or eq?

Artem gmail.com> writes:
> I'd say it should be "if (value eq null) Some (value) else None",
> unless I'm missing some nifty optimizations made in Scala 2.8
> regarding comparison to null.

Indeed this supposedly changed recently (after Beta1 and before RC1):

https://lampsvn.epfl.ch/trac/scala/ticket/3195#comment:3

I haven't tested it myself.

Best,
Ismael

Colin Bullock
Joined: 2009-01-23,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: Option constructor, == or eq?

https://lampsvn.epfl.ch/trac/scala/ticket/3195#comment:3


These two methods do in fact generate identical (correct) bytecode in a fairly recent trunk build.

- Colin

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland