0

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?

3
  • 1
    Yes, we can! Previous problems with pkg objects were fixed. See this answer stackoverflow.com/a/17276060/1296806. Sometimes outer ptrs to containing objects are an issue. Commented Sep 7, 2013 at 3:47
  • Historically, issues.scala-lang.org/browse/SI-1987 and sometimes the presence of package objects hinders recompilation still. I would say POs are best used as intended. Finally, recall that a cake is just a bunch of types layered into a pastry object. Commented Sep 7, 2013 at 4:00
  • Are package objects open, now? Commented Sep 7, 2013 at 4:32

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.