如果没有在类的主构造函数中重命名构造函数参数,B我可以对以下代码进行哪些更改(不更改其函数),以便Scala成功编译它?
例:
class A(var a: Int)
class B(a: Int) extends A(a) {
def inc(value: Int) { this.a += value }
}
Run Code Online (Sandbox Code Playgroud)
错误:
$ scala construct.scala
construct.scala:3: error: reassignment to val
def inc(value: Int) { this.a += value }
^
one error found
Run Code Online (Sandbox Code Playgroud)
我在回答上一个问题时提出了这个问题,"在Scala中,如何在类的主构造函数中定义局部参数?" .
class A(var a: Int)
class B(a: Int) extends A(a) {
def inc(value: Int) { (this: A).a += value }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
359 次 |
| 最近记录: |