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.
Option
as idiomatic way to handle this in Scala:Option(a) getOrElse b
? – KatabaticOption
exists to handle "coalescing" as well as various other ways to deal with a value not being there. And the types force you to deal with the possibility ofNone
, saving you fromnull
-related headaches later. – AnthropoOption
for pure Scala parts but this is need for tight interop with Java apis. But still I think that Kotlin solves this better. – Quesada