Whenever the class
class X {
type T
}
is instantiated while fixing the type member a new Java class is created:
scala> new X() { type T = Int }.getClass.hashCode
res5: Int = 2033908791
scala> new X() { type T = Int }.getClass.hashCode
res6: Int = 1820034148
Yet, when a factory is used
object X {
def apply[TP] = new X { type T = TP }
}
then a single Java class is capable of representing all possible instances:
scala> X.apply[Int].getClass.hashCode
res7: Int = 45806309
scala> X.apply[String].getClass.hashCode
res8: Int = 45806309
Is there are reason for that behaviour or does the Scala compiler simply lack the sensible optimization that a single class would suffice?
It seems that this behaviour is another difference between classes with type members and classes with type parameters (class Y[T]
):
scala> class Y[T]
defined class Y
scala> new Y[Int].getClass.hashCode
res9: Int = 1364679843
scala> new Y[String].getClass.hashCode
res10: Int = 1364679843
Every expression of the form new Something(someArgs) { /* other defs, whether overriding or not */ }
defines a statically distinct type, even if they're structurally equivalent.
On the other hand, evaluating any single such expression multiple times instantiates the same anonymous class.
It has nothing to do with the existence of an abstract type member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With