【发布时间】: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