1

I'm learning Scala and I'm coming from C++ (very little Java experience). Where I work we often use the following pattern:

class SomeClass {
 public:
  class Options {
    ...
  };
  SomeClass(const Options& options);
  ...
};

int main() {
  SomeClass::Options options;
  options.a = ...;
  ...
  SomeClass* sc = new SomeClass(options);
}

How do I emulate that in Scala?

Jasiu
  • 2,674
  • 2
  • 27
  • 27

1 Answers1

5

This is kind of equivalent:

object SomeClass {
    case class Options(option1: String, option2: Boolean)
}

class SomeClass(options: Options) {

    //this is constructor!
    println(options.option1)

}

object Main extends App {
    val options = SomeClass.Options("One", false)
    //or even:    SomeClass.Options(option1 = "One", option2 = false)
    val sc = new SomeClass(options)
}

More about nested classes (don't confuse with inner classes in Java): Static inner classes in scala.

Comments:

  • Options is nested inside SomceClass object, not class
  • Options can be a case class - this way you get immutability and accessors for free
  • In Scala you have one primary constructor defined in very concise way
  • Various: Scala uses pass by reference by default and all variables are actually pointers (less extra symbols compared to C++).
Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • If there are many options, you could even use named parameters to make it clearer. – aioobe May 15 '12 at 13:35
  • Hmm, looks a bit hack-ish. Let's say I have a class (`SomeClass`) and a bunch of related helper classes that only make sense in the context of `SomeClass` (e.g. `Options` in my example). In C++ I could nest all the related helper classes or introduce something like a `detail`/`internal` namespace. What's the preferred way to do that in Scala? Note that the relation is between some classes and a class, not an instance of this class, so I don't require/want dependent types here. – Jasiu May 15 '12 at 15:51
  • @Jasiu You can make the (sub) class private in Scala, and it will only be seen by the object and its class companion. – Daniel C. Sobral May 15 '12 at 17:12