Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of private constructor in Scala?

Tags:

scala

In Java, one of its most common usage is to define a Singleton class. However, since there are no "static" classes in Scala, what are some examples of usages of the Private Constructor?

like image 687
Pravesh Jain Avatar asked Mar 13 '17 14:03

Pravesh Jain


2 Answers

You can access private constructors in the companion object of a class.

That allows you to create alternative ways of creating a new instance of your class without exposing the internal constructor.

I came up with a very quick example of how one might make use of this:

class Foo private(s: String)

object Foo {
  def apply(list: Seq[String]): Foo = {
    new Foo(list.mkString(","))
  }
}

Now you can create new instances of Foo without the new keyword and without exposing the internal constructor, thereby encapsulating the internal implementation.

This can be especially important, as internal implementations might change in the future while the public facing API should remain backwards compatible

like image 98
Luka Jacobowitz Avatar answered Oct 03 '22 08:10

Luka Jacobowitz


The use cases of the private constructors are mostly the same as in Java: sometimes you need a full control of how the instances of your classes are created. Consider scala.immutable.Vector. Its constructor is rather complicated:

final class Vector[+A] private(val startIndex: Int, val endIndex: Int, focus: Int)

This constructor is a complex implementation detail which is likely to be changed in the future and therefore should not be exposed to users. Instead, you provide simple factory methods which hide all that complexity of creating instances of vectors: Vector.apply(), Vector.tabulate(), Vector.fill(), ...

like image 25
ZhekaKozlov Avatar answered Oct 03 '22 06:10

ZhekaKozlov