score:7

Accepted answer

in scala there are two idiomatic ways how to achieve that.

  1. constructor private to the class and companion object.

factory has access to constructor, while anyone else doesn't:

class foo private[foo](val x: int)

object foo {
  def apply(x:int) = new foo(x)
}

val foo = new foo(1)  // cannot compile
val foo1 = foo(1) //compiles fine
  1. sealed abstract class.

in scala sealed class can be extended only in the same source file it is defined. i suggest to make foo sealed abstract class and return anonymous child of foo in object's apply method.

sealed abstract class foo(val x:int)

object foo {
  def apply(x:int):foo = new foo(x) {}
}

in this case foo can be created nowhere except the file where it is defined.

upd: actually, this question was already discussed on stackoverflow.

upd2: added brief overview of both methods.


Related Query

More Query from same tag