为什么我的对象不是包< root>的成员?如果在单独的源文件中? [英] Why is my object not a member of package <root> if it's in a separate source file?

查看:67
本文介绍了为什么我的对象不是包< root>的成员?如果在单独的源文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问根包中定义的对象时遇到问题.如果我将所有代码都放在一个文件中,则可以正常工作,但是当我将其拆分为两个文件时,就无法通过编译器.

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不是root软件包的成员,那么 在哪里?

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.

来源 Scala参考§9.2程序包.

但是不要问我,如果您在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)
  }
}

这篇关于为什么我的对象不是包&lt; root&gt;的成员?如果在单独的源文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆