tags:

views:

379

answers:

2

I've been curious about the impact of not having an explicit primary constructor in Scala, just the contents of the class body.

In particular I suspect that the private or protected constructor pattern, i.e. controlling construction through the companion object or another class or object's methods might not have an obvious implementation.

Am I wrong? if so how is it done please?

+7  A: 

You can declare the default constructor as private/protected by inserting the appropriate keyword between the class name and the paramater list, like this:

class Foo private () { 
  /* class body goes here... */
}
Aleksander Kmetec
Thanks Aleksander, Can you please tell me whether this is presented in one of the scala books or in the language specification? Sorry I can't upvote yet.
Don Mackenzie
I just glanced over "Programming Scala"'s explanation of constructors (pages 92-95) and I don't see it mentioned there.I actually found the answer to your question in an old changelog, but I've never seen it mentioned anywhere else before. Link: http://www.scala-lang.org/node/43#2.4.0
Aleksander Kmetec
Pag 414 of "Programming in Scala". Page 97 of Wampler's Programming Scala. Page 60 of Subramaniam's Programming Scala. I don't have a PDF of Beginning Scala with me right now to check it out.
Daniel
Oh, I see it now on page 97. Thanks.
Aleksander Kmetec
Thanks both for the further research, I've got the Wampler book, but only on my phone and clearly haven't read it thoroughly but I've found that it complements the Odersky book surprisingly well.
Don Mackenzie
+8  A: 

Aleksander's answer is correct, but Programming in Scala offers an additional alternative:

trait Foo {
 // interface
}

object Foo {
  def apply(...) = // public constructor

  private class FooImpl(...) extends Foo { ... } // real class
}
Daniel
That's clever, needless to say I didn't realise traits could act as surrogates for classes in the construction paradigm.
Don Mackenzie
In this particular case, they are just an interface. Though you could put some code in it. Alas, there's a bug in my example, which I'm correcting right now...
Daniel
Just been giving this technique a bit of thought. The trait must convey the complete non private interface of the required implementation of a "Foo" but in return for this constraint you get a lot of freedom in how you provide the implementation while keeping with the spirit of what apply should return.
Don Mackenzie