【问题标题】:Accessibility of scala constructor parametersscala构造函数参数的可访问性
【发布时间】:2019-10-02 04:02:30
【问题描述】:

在确定 Scala 的构造函数参数范围时需要明确

根据此链接https://alvinalexander.com/scala/how-to-control-visibility-constructor-fields-scala-val-var-private#comment-13237,只要将构造函数参数标记为私有,就不会创建 getter 和 setter 方法。但是,即使参数被标记为私有,我在此处提供的代码也可以正常工作。 我浏览了这个 StackOverflow 链接Do scala constructor parameters default to private val?。这个和上面的矛盾。有人可以解释一下。事实上,代码段可以在 StackOverflow 链接中找到。

class Foo(private val bar: Int) {
    def otherBar(f: Foo) {
        println(f.bar) // access bar of another foo
    }
}

以下行运行良好:

val a = new Foo(1)
a.otherBar(new Foo(3))

打印 3。

根据第一个链接,代码应该会导致编译错误,因为参数是私有的。

【问题讨论】:

    标签: scala constructor


    【解决方案1】:

    如果您查看scala language specificationprivate 修饰符允许访问

    来自直接封闭的模板及其伴随模块或伴随类。

    要仅允许从您的实例内部进行访问,您可以使用修饰符 private[this]。代码

    class Foo(private[this] val bar: Int) {
      def otherBar(f: Foo) {
        println(f.bar) // access bar of another foo
      }
    }
    

    结果

    [error] .../src/main/scala/sandbox/Main.scala:9:17: value bar is not a member of sandbox.Foo
    [error]       println(f.bar) // access bar of another foo
    [error]                 ^
    [error] one error found
    

    【讨论】:

    • 为什么private [this] val barbar 更好?
    • 如果只使用bar,它只是一个构造函数参数,不会在Foo类中创建成员变量。原发帖人问为什么可以从另一个实例访问private 成员变量
    • 那么为什么有一个成员变量比没有一个成员变量更好呢?和反射有关系吗?创建不需要的成员还有什么其他原因?
    • 如果不需要成员变量,就不要使用它。我同意这一点。但据我了解,最初的问题是关于 Scala 中 private 成员的可访问性规则。
    • 感谢 Harald 的回答!当我们在构造函数参数中说“private val bar: Int”(没有“this”)时,将使用 getter 和 setter 方法创建一个名为“bar”的私有字段。如果这是正确的,那么我在问题中提供的链接需要更正。
    【解决方案2】:

    如果你想要一个只在类内部可见的构造函数参数,不要让它成为一个成员,只要让它成为一个普通的函数参数:

    class Foo(bar: Int) {
      def otherBar(f: Foo) {
        println(f.bar) // Fails: value bar is not a member of Foo
      }
    }
    

    构造函数内的所有代码仍然可以访问bar,但它不是Foo的成员,因此在构造函数外不可见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2023-04-02
      • 2013-03-16
      • 2012-12-25
      • 2015-08-12
      相关资源
      最近更新 更多