【问题标题】:What is the difference between private modifier position in a Scala class declaration?Scala类声明中的私有修饰符位置有什么区别?
【发布时间】:2016-07-09 08:03:24
【问题描述】:

假设我有两个类:

private[example] class PoorInt    extends Int
class RichInt    private[example] extends Int

问题是这些类声明中的私有修饰符位置有什么区别?

【问题讨论】:

    标签: scala


    【解决方案1】:

    第一个是指类的范围,即不能在包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

    【讨论】:

    • 这很奇怪,因为当我将伴随对象添加到 PoorInt 时,一切正常:object PoorInt { def apply() = new PoorInt }。它使 PoorInt 可访问。
    • 在这种情况下,“可访问”是什么意思?同伴可以访问,而类本身不能访问(由于 private 修饰符),例如你可以写val y = PoorInt(),因为companion 和apply 方法都是公共的,但是你不能写val y: PoorInt = PoorInt(),因为类型本身是私有的。请提供一个具体的例子,以便其他人可以准确地重现该问题。
    • @Finkelson 没什么奇怪的——伴生对象可以访问其伴生类的私有部分(反之亦然)。
    • 如果我要声明这样的类class B private () { def apply(i: Int) = new B }。在这种情况下,通过 new B(1) 在另一个包中实例化 B 会导致错误,但是我声明了一个公共构造函数 apply(i: Int)。所以我猜private 限制传播到所有构造函数。
    • @Finkelson 如果你想重载/创建另一个构造函数,你需要使用this 作为方法名,即def this(i: Int) = this(),而不是你建议的def apply(i: Int) = new B。 OTOH,您可以将此apply 方法放在B 的伴随对象中用于相同目的。
    猜你喜欢
    • 2015-05-08
    • 2015-11-26
    • 1970-01-01
    • 2011-01-15
    • 2020-08-25
    • 1970-01-01
    • 2019-02-22
    • 2011-11-11
    • 2013-05-21
    相关资源
    最近更新 更多