【问题标题】:Explain why import scala.Predef.String fails build解释为什么 import scala.Predef.String 构建失败
【发布时间】:2013-07-17 02:40:18
【问题描述】:

我发现 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

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

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

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

【问题讨论】:

    标签: scala import predef


    【解决方案1】:

    我在来源中找到了答案。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 2018-01-10
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      相关资源
      最近更新 更多