What is the use of private constructor in Scala?

后端 未结 2 787
北海茫月
北海茫月 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:26

    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

提交回复
热议问题