Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

nested - What's the motive behind Chained Package clauses in Scala?

Chained package clause were introduced in Scala 2.8, as described by Martin Odersky on the Scala site. I don't quite get the intuition behind this.

Following was the example in the Scala book for the nested packages:

package bobsrockets {
    package navigation {
        // In package bobsrockets.navigation
        class Navigator
        package tests {
            // In package bobsrockets.navigation.tests
            class NavigatorSuite
        }
    }
}

This use case of nested packages made sense because we could use multiple nested packages in the same file, however the new syntax achieves the same thing as before but without the brackets. Won't it be difficult to separate out the package in between the succinct Scala code?

package bobsrockets
package navigation
// In package bobsrockets.navigation
class Navigator
package tests
// In package bobsrockets.navigation.tests
class NavigatorSuite

Please let me know if I'm getting it the wrong way or if I misunderstand the concept.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use the syntax without brackets in the way your example shows, but I never saw this in "real life". I think almost always the new feature is simply used to get parent packages in scope:

package bobrockets.navigation
package tests

//now the content of bobrockets.navigation is in scope

This is basically the same as writing

package bobrockets.navigation.test
import bobrockets.navigation._

However, the first version follows the DRY principle. E.g. if you rename the package bobrockets to robertsrockets, you could forget to change the import in the second version (which might point to some "old" code), which is impossible in the first version. In a sense, this (together with the possibility to have modifiers like private[bobsrockets.navigation]) allows to use package groups as "modules" or "superpackages" with a very lightweight syntax.

This is the main usage I'm aware of, but Scala shows often surprising synergy effects, and is blurring the lines (e.g. between objects, packages and package objects, between vals and objects, between defs and functions etc) in interesting ways. So the future will show if this feature has other useful applications.

[Update] Here is a new article about this topic by Martin Odersky himself: http://www.artima.com/scalazine/articles/chained_package_clauses_in_scala.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...