为什么我的对象不是包<root>的成员如果它在一个单独的源文件中? [英] Why is my object not a member of package <root> if it's in a separate source file?
问题描述
我在访问根包中定义的对象时遇到问题.如果我将所有代码都放在一个文件中,它可以正常工作,但是当我将它分成两个文件时,我无法通过编译器.
I'm having a problem accessing an object defined in the root package. If I have all my code in one file, it works fine, but when I split it across two files, I can't get it past the compiler.
这很好用:
全部在一个名为 packages.scala
的文件中:
All in one file called packages.scala
:
object Foo
val name = "Brian"
}
package somepackage {
object Test extends App {
println(Foo.name)
}
}
证人:
$ scalac packages.scala
$ scala -cp . somepackage.Test
Brian
但如果我将代码拆分为两个文件:
But if I split the code across two files:
packages.scala
object Foo {
val name = "Brian"
}
packages2.scala
package somepackage {
object Test extends App {
println(Foo.name)
}
}
一切都失败了:
$ scalac packages.scala packages2.scala
packages2.scala:3: error: not found: value Foo
所以我尝试将 Foo
的引用设为绝对:
So I try to make the reference to Foo
absolute:
...
println(_root_.Foo.name)
...
但这也不起作用:
$ scalac packages.scala packages2.scala
packages2.scala:3: error: object Foo is not a member of package <root>
如果 Foo
不是根包的成员,那么它到底在哪里 ?
If Foo
is not a member of the root package, where on earth is it?
推荐答案
我认为这是规范中的相关部分:
I think this is the relevant part in the spec:
包装之外的顶级定义被假定注入到一个特殊的空包中.该包无法命名,因此无法导入.但是,空包的成员彼此可见,无需限定.
Top-level definitions outside a packaging are assumed to be injected into a special empty package. That package cannot be named and therefore cannot be imported. However, members of the empty package are visible to each other without qualification.
但是如果你在 packages2.scala
中有以下内容,不要问我为什么它有效:
But don’t ask me why it works if you have the following in packages2.scala
:
object Dummy
package somepackage {
object Test extends App {
println(Foo.name)
}
}
这篇关于为什么我的对象不是包<root>的成员如果它在一个单独的源文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!