Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement `??` (a null coalescing operator from C#) in Scala that does not use reflection?

I've found somewhere an implementation of C# null coalescing operator '??':

implicit def coalescingOperator[T](pred: T) = new {
  def ??[A >: T](alt: =>A) = if (pred == null) alt else pred
}

It can be then used like a ?? b which means if (a == null) b else a.

And after decompiling the class files I saw that it produces code with reflection (in Scala 2.8.1).

Why it generates reflection and is it possible to modify that code so it would not generate reflection?

like image 394
TN. Avatar asked May 28 '12 16:05

TN.


Video Answer


1 Answers

Scala doesn't have the same idea of anonymous classes as Java does. If you say something like

new {
  def fish = "Tuna"
}

then it will interpret all uses of the new method as requiring a structural type, i.e. the same as

def[T <: {def fish: String}](t: T) = t.fish

which needs to use reflection since there's no common superclass. I don't know why it's this way; it's exactly the wrong thing to do for performance, and usually isn't what you need.

Regardless, the fix is easy: create an actual class, not an anonymous one.

class NullCoalescer[T](pred: T) {
  def ??[A >: T](alt: => A) = if (pred == null) alt else pred
}
implicit def anyoneCanCoalesce[T](pred: T) = new NullCoalescer(pred)

In 2.10, it still does the arguably wrong thing, but (1) it will throw warnings at you for using reflection this way (so at least you'll know when it's happened) unless you turn them off, and (2) you can use a shorter version implicit class /* blah blah */ and skip the implicit def which just adds boilerplate.

like image 124
Rex Kerr Avatar answered Oct 06 '22 09:10

Rex Kerr