Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot specialize a Scala method with specializable trait as return type

trait Eq[@specialized -X] {
  def eq(x: X, y: X): Boolean
}

trait Keyed[@specialized(Int) X] {
  def eqOnKey: Eq[X]
}

The method eqOnKey is not specialized in the generated class Keyed$mcI$sp.

How can I specialize this method, i.e. making the return type of method eqOnKey$mcI$sp in class Keyed$mcI$sp to be Eq$mcI$sp?

like image 309
Tongfei Chen Avatar asked Feb 02 '16 19:02

Tongfei Chen


1 Answers

If you extend Keyed with Eq, you end up with a specialized eq method. This might not work for you, depending on your use case.

trait Eq[@specialized -X] {
  def eq(x: X, y: X): Boolean
}

trait Keyed[@specialized(Int) X] extends Eq[X]


class Foo extends Keyed[Int] {
  def eq(x: Int, y: Int) : Boolean = x == y
}

Will generate the following bytecode for Foo

  public boolean eq$mcI$sp(int, int);
    Code:
       0: iload_1
       1: iload_2
       2: if_icmpne     9
       5: iconst_1
       6: goto          10
       9: iconst_0
      10: ireturn

  public boolean eq(java.lang.Object, java.lang.Object);
    Code:
       0: aload_0
       1: aload_1
       2: invokestatic  #146                // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
       5: aload_2
       6: invokestatic  #146                // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
       9: invokevirtual #148                // Method eq:(II)Z
      12: ireturn
like image 161
S15 Avatar answered Oct 21 '22 21:10

S15