0

鉴于:

$cat build.sbt
scalaVersion := "2.12.1"

$cat src/main/scala/net/X.scala
package net 

trait Foo 
object X {

    val a: Int with Foo = 42.asInstanceOf[Int with Foo]

    println(a + a)

}

通过 编译后sbt compile,我javap 'd 输出class文件:

$javap target/scala-2.12/classes/net/X\$.class 
Compiled from "X.scala"
public final class net.X$ {
  public static net.X$ MODULE$;
  public static {};
  public int a();
}

$javap target/scala-2.12/classes/net/X.class 
Compiled from "X.scala"
public final class net.X {
  public static int a();
}

为什么a会有类型,int

我已经指定了一种Int with Fooin object X

4

1 回答 1

2

这就是 Scala 中所有交集类型都被编译为 JVM 字节码的方式。JVM 无法表示类似Int with Foo的东西,因此编译器将类型擦除为第一个“简单”类型:Int在这种情况下。这意味着如果你使用a像 a 这样的值Foo,编译器必须在字节码中插入一个强制转换。

查看以下 REPL 会话:

Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111).
Type in expressions for evaluation. Or try :help.

scala> trait Foo { def foo = "foo" }
defined trait Foo

scala> trait Bar { def bar = "bar" }
defined trait Bar

scala> class FooBar extends Foo with Bar
defined class FooBar

scala> class Test { val foobar: Foo with Bar = new FooBar }
defined class Test

scala> object Main {
     |   def main(): Unit = {
     |     val test = new Test().foobar
     |     println(test.foo)
     |     println(test.bar)
     |   }
     | }
defined object Main

scala> :javap -p -filter Test
Compiled from "<console>"
public class Test {
  private final Foo foobar;
  public Foo foobar();
  public Test();
}

scala> :javap -c -p -filter Main
Compiled from "<console>"
  ...
  public void main();
    Code:
      ...
      15: invokeinterface #62,  1           // InterfaceMethod Foo.foo:()Ljava/lang/String;
      ...
      27: checkcast     #23                 // class Bar
      30: invokeinterface #69,  1           // InterfaceMethod Bar.bar:()Ljava/lang/String;
      ...

Int with Foo其实是个特例。Int是最终类型并且Foo是特征。显然编译器更喜欢最终类型和类而不是特征。所以在Foo with Barwhere Foois a trait and Baris a class 中,类型仍然被擦除为Bar而不是Foo.

于 2017-01-07T19:18:37.490 回答