What is the use of private constructor in Scala?

后端 未结 2 867
北海茫月
北海茫月 2021-01-02 23:09

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 Privat

2条回答
  •  感情败类
    2021-01-02 23:28

    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(), ...

提交回复
热议问题