我发现Scala import非常奇怪。
我写了样本课:
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)
答案 0 :(得分: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问题跟踪系统中创建bug,所以我做了。 https://issues.scala-lang.org/browse/SI-7672