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?
Scala doesn't have the same idea of anonymous classes as Java does. If you say something like
then it will interpret all uses of the new method as requiring a structural type, i.e. the same as
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.
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 theimplicit def
which just adds boilerplate.