了解编译的Scala文件中的类型

时间:2017-01-07 18:19:17

标签: scala javap

假设:

$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输出了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 Foo中指定了一种object X

1 个答案:

答案 0 :(得分:2)

这就是将Scala中的所有交集类型编译为JVM字节码的方式。 JVM无法表示Int with Foo之类的内容,因此编译器会将类型删除为第一个“简单”类型:在这种情况下为Int。这意味着如果您使用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 Bar Foo中,Bar是一个特征而Bar是一个类,该类型仍会被删除为Foo而不是def ChangePassword(): while True: email=input("Enter the email you want to change the password for") res=BinarySearch(logindata,email) if res: break