Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

scala - 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.

This works fine:

All in one file called packages.scala:

object Foo
  val name = "Brian"
}

package somepackage {
  object Test extends App {
    println(Foo.name)
  }
}

Witness:

$ 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)
  }
}

it all fails:

$ scalac packages.scala packages2.scala
packages2.scala:3: error: not found: value Foo

So I try to make the reference to Foo absolute:

...
    println(_root_.Foo.name)
...

But that doesn't work either:

$ scalac packages.scala packages2.scala
packages2.scala:3: error: object Foo is not a member of package <root>

If Foo is not a member of the root package, where on earth is it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Source Scala Reference §9.2 Packages.

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)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...