简体   繁体   English

无法将具有特殊特征的Scala方法专门用作返回类型

[英]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 . 方法eqOnKey不是专门生成的类Keyed$mcI$sp

How can I specialize this method, ie making the return type of method eqOnKey$mcI$sp in class Keyed$mcI$sp to be Eq$mcI$sp ? 我怎样才能专注这个方法,即制作方法的返回类型eqOnKey$mcI$spKeyed$mcI$spEq$mcI$sp

If you extend Keyed with Eq, you end up with a specialized eq method. 如果你使用Eq扩展Keyed,你最终会得到一个专门的eq方法。 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 将为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM