3

我发现 Scala 导入存在非常奇怪的问题。

我写了示例类:

package test_scala_predef

object App extends App {

  classOf[T]
  println( "Hello World!" )
}

class T {

}

这个类编译没有任何错误。

但是,如果我添加

import scala.Predef.String

然后我得到编译错误:

[INFO] Compiling 1 source files to /home/uthark/src/_/test_scala_predef/target/classes at 1374028063588
[ERROR] /home/uthark/src/_/test_scala_predef/src/main/scala/test_scala_predef/App.scala:10: error: not found: value classOf
[INFO]   classOf[T]
[INFO]   ^
[ERROR] /home/uthark/src/_/test_scala_predef/src/main/scala/test_scala_predef/App.scala:11: error: not found: value println
[INFO]   println( "Hello World!" )
[INFO]   ^
[ERROR] two errors found

我有一个想法,在我添加特定的 import from之后,不添加scala.Predef隐式 import of 。scala.Predef._但是我在 Scala 文档中找不到任何关于它的信息。谁能指出我文档中的相关部分?

我检查了Scala Language Specification (PDF),第 12.5 节涵盖scala.Predef但也没有发现任何相关内容。

我使用可用的最新稳定 scala 版本(目前为 2.10.2)

4

1 回答 1

3

我在来源中找到了答案。

https://github.com/scala/scala/blob/master/src/compiler/scala/tools/nsc/typechecker/Contexts.scala

  /** List of symbols to import from in a root context.  Typically that
   *  is `java.lang`, `scala`, and [[scala.Predef]], in that order.  Exceptions:
   *
   *  - if option `-Yno-imports` is given, nothing is imported
   *  - if the unit is java defined, only `java.lang` is imported
   *  - if option `-Yno-predef` is given, if the unit body has an import of Predef
   *    among its leading imports, or if the tree is [[scala.Predef]], `Predef` is not imported.
   */
  protected def rootImports(unit: CompilationUnit): List[Symbol] = {
    assert(definitions.isDefinitionsInitialized, "definitions uninitialized")

    if (settings.noimports) Nil
    else if (unit.isJava) RootImports.javaList
    else if (settings.nopredef || treeInfo.noPredefImportForUnit(unit.body)) {
      debuglog("Omitted import of Predef._ for " + unit)
      RootImports.javaAndScalaList
    }
    else RootImports.completeList
  }

这回答了我的问题。

关键语句是这样的:

例外:...如果单元主体在其主要导入中导入 Predef

此外,在#scala irc 上的聊天中,有人建议在 Scala 问题跟踪系统中创建错误,所以我做到了。https://issues.scala-lang.org/browse/SI-7672

于 2013-07-17T02:58:46.837 回答