本文介绍了如何在 REPL 中检查隐式/丰富转换和实现的特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

to 不是 Int 的成员函数时,Scala 中的某些东西对我来说似乎是不透明的:

Some things in Scala seems opaque to me such as the following when to is not a member function of Int:

1.to(4)

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

Can I examine what behavior caused this (an implicit conversion or trait or other) without consulting the language reference? And that too in the REPL?

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

If the REPL can't help, is there some friendly alternative?

推荐答案

使用 Scala 2.9:

With 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:

With Scala 2.10 or 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)

这篇关于如何在 REPL 中检查隐式/丰富转换和实现的特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:49