Reputation: 841
I'm a new to scala, here's a question:
object Models {
class A1 { // some methods }
class A2 { // some methods }
}
This code works and Models seems to be treated as some sort of a scoping unit - I can import it wherever I need to. Is this a normal practice? Can I use this as a way to scope parts of a package? There also seems to be a package object, which I guess behaves similarly. Are there any problems with this method that I should know about?
Upvotes: 0
Views: 485
Reputation: 5449
It's normal practice and can be used as needed. You can group some things that you might not normally be able to just inside a file (Consts for example).
val DefaultKey="12345" //not legal inside a file outside of a class or object
class A (key:String) {
}
Legal version:
package com.mytest
object KeyExchange {
val DefaultKey="12345" //now legal
class A (key:String) {
}
}
use:
object Test extends App { //extending App is like a main method
import com.mytest.KeyExchange._ //can use import statement here, bringing in class A and the const.
val myA = new A(DefaultKey)
}
The package object is kind of like this concept, except the things placed inside of it become available to the classes and traits defined as part of that package (com.mytest for example.) This is the place you might put const items that the classes will frequently use, or more importantly implicit functions and objects. You could just place all of those things in a separate file, and object, but then you'd have to import them explicitly each time. You don't have to use package objects. My understanding is that this should be used sparingly, for items you're certain most classes can make use of.
reference: http://www.scala-lang.org/docu/files/packageobjects/packageobjects.html
Upvotes: 2