Private and protected constructor in Scala

后端 未结 2 1977
一个人的身影
一个人的身影 2020-12-07 14:42

I\'ve been curious about the impact of not having an explicit primary constructor in Scala, just the contents of the class body.

In particular, I suspect that the pr

相关标签:
2条回答
  • 2020-12-07 14:50

    Aleksander's answer is correct, but Programming in Scala offers an additional alternative:

    sealed trait Foo {
     // interface
    }
    
    object Foo {
      def apply(...): Foo = // public constructor
    
      private class FooImpl(...) extends Foo { ... } // real class
    }
    
    0 讨论(0)
  • 2020-12-07 15:07

    You can declare the default constructor as private/protected by inserting the appropriate keyword between the class name and the parameter list, like this:

    class Foo private () { 
      /* class body goes here... */
    }
    
    0 讨论(0)
提交回复
热议问题