Scala delcaration of a package - one of the ways causes the visibility of package objects, and the other does not?

In foo/bar/my_package/package.scala :

 package foo.bar package object my_package { type SomeType = java.lang.String } 

Then in foo/bar/my_package/my_sub/MyClass.scala

 package foo.bar.my_package.my_sub class MyClass { var x: SomeType = _ } 

This does not compile; SomeType not found. If I change MyClass.scala to

 package foo.bar.my_package package my_sub class MyClass { var x: SomeType = _ } 

Everything works perfectly. What is the difference!?!??!

(This is Scala 2.8.1)

+4
source share
2 answers

Package declarations, such as imports, give you access to everything inside them. Therefore when you

 package foo.bar.my_package 

then you have everything that would be if you did

 import foo.bar.my_package._ 

In addition, declaring a package on a single line means that everything below applies to this package:

 package foo.bar.my_package { package my_sub { class MyClass { var x: SomeType = _ } } } 

(which is equivalent to:

 package foo.bar.my_package package my_sub class MyClass { var x: SomeType = _ } 

)

so that you can see how the contents of foo.bar.my_package should be in scope in this case. Otherwise, you only have the contents of foo.bar.my_package.my_sub , which does not include SomeType .

+5
source

This is a matter of visibility.

 package foo.bar.my_package.my_sub class MyClass { var x: SomeType = _ } 

When you declare x , the following things are visible:

  • Each member of MyClass
  • Everything inside foo.bar.my_package.my_sub
  • Each member of scala.Predef
  • Everything inside scala
  • Everything inside java.lang

SomeType is not in any of them.

On the other hand, when you do:

 package foo.bar.my_package package my_sub class MyClass { var x: SomeType = _ } 

Then visibility:

  • Each member of MyClass
  • Everything inside foo.bar.my_package.my_sub
  • Everything inside foo.bar.my_package
  • Each member of scala.Predef
  • Everything inside scala
  • Everything inside java.lang

And SomeType is inside foo.bar.my_package , which is the second line.

A related question is why it works this way. You can start here, although there is a question about which . I do not really like the answer to this question, although it really does not address the reasons for this. He refers to a link to a page on scala-lang about the new Scala 2.8 features in which Odersky explains the reasons.

+2
source

All Articles