简体   繁体   English

scala构造函数参数的可访问性

[英]Accessibility of scala constructor parameters

Clarity needed in determining the scope of Scala's constructor parameter 确定Scala构造函数参数的范围时需要清晰度

As per this link https://alvinalexander.com/scala/how-to-control-visibility-constructor-fields-scala-val-var-private#comment-13237 , whenever a constructor parameter is labelled as private, then no getter and setter methods will be created. 根据这个链接https://alvinalexander.com/scala/how-to-control-visibility-constructor-fields-scala-val-var-private#comment-13237 ,每当构造函数参数被标记为私有时,就没有getter和setter方法将被创建。 But the code I have provided here works fine even though the parameter is labelled as private. 但是我在这里提供的代码工作正常,即使参数被标记为私有。 I went through this StackOverflow link Do scala constructor parameters default to private val? 我经历了这个StackOverflow链接do scala构造函数参数默认为private val吗? . This one & the above contradicts. 这一点与上述矛盾。 Can someone please explain. 有人可以解释一下。 The code segment is, in fact, available in the StackOverflow link. 事实上,代码段在StackOverflow链接中可用。

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

The below line runs fine: 以下行正常运行:

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

It prints 3. 它打印3。

As per the first link, the code should result in compile error because the parameter is private. 根据第一个链接,代码应该导致编译错误,因为参数是私有的。

If you have a look at the scala language specification the private modifier allows access 如果你看一下scala语言规范,那么private修饰符允许访问

from within the directly enclosing template and its companion module or companion class. 从直接封闭的模板及其伴随模块或伴随类中。

To allow access only from your inside the instance you can use the modifier private[this] . 要仅允许从实例内部访问,可以使用修饰符private[this] The code 代码

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

results in 结果是

[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

If you want a constructor parameter that is only visible inside the class, don't make it a member, just make it a normal function parameter: 如果你想要一个只在类中可见的构造函数参数,不要使它成为一个成员,只需使它成为一个普通的函数参数:

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

All the code inside the constructor can still access bar , but it is not a member of Foo and therefore is not visible outside the constructor. 构造函数中的所有代码仍然可以访问bar ,但它不是Foo的成员,因此在构造函数外部不可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM