如何检查REPL中的隐式/丰富转换和实现的特征

时间:2012-04-03 19:02:45

标签: scala

to不是Int的成员函数时,Scala中的某些内容对我来说似乎不透明,如下所示:

1.to(4)

我可以在不咨询语言参考的情况下检查导致此行为(隐式转换或特征或其他)的行为吗?这也是REPL

如果REPL无法提供帮助,是否有一些友好的替代方案?

1 个答案:

答案 0 :(得分:14)

使用Scala 2.9:

  ~/code/scala scala -Xprint:typer -e "1 to 4"
[[syntax trees at end of typer]]// Scala source: scalacmd4469348504265784881.scala
package <empty> {
  final object Main extends java.lang.Object with ScalaObject {
    def this(): object Main = {
      Main.super.this();
      ()
    };
    def main(argv: Array[String]): Unit = {
      val args: Array[String] = argv;
      {
        final class $anon extends scala.AnyRef {
          def this(): anonymous class $anon = {
            $anon.super.this();
            ()
          };
          scala.this.Predef.intWrapper(1).to(4)
        };
        {
          new $anon();
          ()
        }
      }
    }
  }
}

使用Scala 2.10或2.11:

scala> import reflect.runtime.universe
import reflect.runtime.universe

scala> val tree = universe.reify(1 to 4).tree
tree: reflect.runtime.universe.Tree = Predef.intWrapper(1).to(4)

scala> universe.showRaw(tree)
res0: String = Apply(Select(Apply(Select(Ident(scala.Predef), newTermName("intWrapper")), List(Literal(Constant(1)))), newTermName("to")), List(Literal(Constant(4))))

scala> universe.show(tree)
res1: String = Predef.intWrapper(1).to(4)