Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict class constructor visibility in Scala 2.9

Tags:

scala

Greetings,

How can I make the Foo constructor visible only to this package (unit test + companion object) ?

I don't want to be able to instantiate Foo outside of this 2 files...

Foo.scala

package project.foo

class Foo(val value: String)

object Foo {
  def generate: Foo = new Foo("test")
}

FooSpec.scala

package project.foo

import org.spec2.mutable._

class FooSpec extends Specification {
  "Foo" should {
    "be constructed with a string" {
      val foo = new Foo("test")
      foo.value must be "test"
    }
  }
}

I'm using Scala 2.9

like image 804
Alois Cochard Avatar asked May 19 '11 07:05

Alois Cochard


1 Answers

Try this:

package project.foo
class Foo private[foo] (value: String)

Then the constructor of Foo is only accessible from the foo package.

You can read more about Scala's visibility (look especially for scoped private and scoped protected) here.

like image 184
Jean-Philippe Pellet Avatar answered Oct 31 '22 13:10

Jean-Philippe Pellet