【发布时间】:2016-07-09 08:03:24
【问题描述】:
假设我有两个类:
private[example] class PoorInt extends Int
class RichInt private[example] extends Int
问题是这些类声明中的私有修饰符位置有什么区别?
【问题讨论】:
标签: scala
假设我有两个类:
private[example] class PoorInt extends Int
class RichInt private[example] extends Int
问题是这些类声明中的私有修饰符位置有什么区别?
【问题讨论】:
标签: scala
第一个是指类的范围,即不能在包example之外访问PoorInt。
第二个是RichInt的构造函数的范围,你没有明确提供,即你不能在包example之外使用它的构造函数。
例如:
// somewhere outside package example ...
val x = new RichInt // doesn't compile. Constructor is private
val y : PoorInt = ... // doesn't compile. PoorInt is not accessible from here
def f(x: PoorInt) = ... // doesn't compile. PoorInt is not accessible from here
你也可以看到this question。
【讨论】:
object PoorInt { def apply() = new PoorInt }。它使 PoorInt 可访问。
val y = PoorInt(),因为companion 和apply 方法都是公共的,但是你不能写val y: PoorInt = PoorInt(),因为类型本身是私有的。请提供一个具体的例子,以便其他人可以准确地重现该问题。
class B private () { def apply(i: Int) = new B }。在这种情况下,通过 new B(1) 在另一个包中实例化 B 会导致错误,但是我声明了一个公共构造函数 apply(i: Int)。所以我猜private 限制传播到所有构造函数。
this 作为方法名,即def this(i: Int) = this(),而不是你建议的def apply(i: Int) = new B。 OTOH,您可以将此apply 方法放在B 的伴随对象中用于相同目的。