Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do scala constructor parameters default to private val?

People also ask

How do you make a Scala constructor private?

In Scala, only a primary constructor is allowed to invoke a superclass constructor. In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list.

What is constructor in Scala?

Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.

Do Scala objects have constructors?

By default, every Scala class has a primary constructor. The primary constructor consists of the constructor parameters, the methods called in the class body, and the statements executed in the body of the class.


bar: Int

This is barely a constructor parameter. If this variable is not used anywhere except the constructor, it remains there. No field is generated. Otherwise private val bar field is created and value of bar parameter is assigned to it. No getter is created.

private val bar: Int

Such declaration of parameter will create private val bar field with private getter. This behavior is the same as above no matter if the parameter was used beside the constructor (e.g. in toString() or not).

val bar: Int

Same as above but Scala-like getter is public

bar: Int in case classes

When case classes are involved, by default each parameter has val modifier.


In the first case, bar is only a constructor parameter. Since the main constructor is the content of the class itself, it is accessible in it, but only from this very instance. So it is almost equivalent to:

class Foo(private[this] val bar:Int)

On the other hand, in the second case bar is a normal private field, so it is accessible to this instance and other instances of Foo. For example, this compiles fine:

class Foo(private val bar: Int) {
  def otherBar(f: Foo) {
    println(f.bar) // access bar of another foo
  }
}

And runs:

scala> val a = new Foo(1)
a: Foo = Foo@7a99d0af

scala> a.otherBar(new Foo(3))
3

But this doesn't:

class Foo(bar: Int) {
  def otherBar(f: Foo) {
    println(f.bar) // error! cannot access bar of another foo
  }
}