Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Why does fixing a type member create a Java subclass?

Tags:

scala

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
like image 930
Stefan Avatar asked Feb 06 '14 17:02

Stefan


1 Answers

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.

like image 146
Randall Schulz Avatar answered Nov 15 '22 03:11

Randall Schulz