Scala 趣题 13 私有的构造函数


首先要知道,私有成员对相伴对象是可见的

即使如此,下面的代码会有编译错误吗?



  object Lives {
    class Private {
      def foo1: Any = new Private.C1
      def foo2: Any = new Private.C2
    }
    
    object Private {
      class C1 private {}
      private class C2 {}
    }
  }




































解释


Explanation


Object Private defines two classes C1 and C2. C2 is a private class which is only accessible in object Private and its companion class, whereas C1 is a public class with a private default constructor, so this class can only be instantiated within class C1.


As a consequence, method foo2 just compiles fine (as the private class C2 is visible in class Private), whereas the implementation of method foo1 reports the following compiler error:


error: constructor C1 in class C1 cannot be accessed in class Private

         def foo1: Any = new Private.C1

                         ^


Note, that the result type of method foo2 has to be set to a base type of Private.C2, otherwise the result type of this method would be a type which is invisible by any caller outside of class/object Private (the compiler would report that the private class C2 escapes its defining scope). For method foo1 this is not necessary.


你可能感兴趣的:(scala)