scala 主构造函数_在Scala中,如何在类的主构造函数中定义局部参数?
在Scala中,如何在不是數(shù)據(jù)成員的類的主構(gòu)造函數(shù)中定義局部參數(shù),例如,僅用于初始化基類中的數(shù)據(jù)成員?
例如,在下面的代碼中,如何在B類的主構(gòu)造函數(shù)中正確定義參數(shù)b,以便它只生成臨時(shí)本地參數(shù)而不是數(shù)據(jù)成員?
class A(var a: Int)
class B(?b?) extends A(b)
Randall,你的答案解釋了當(dāng)我引入一個(gè)增加屬性a的方法inc時(shí)Scala編譯器抱怨的原因,同時(shí)也改變了B類構(gòu)造函數(shù)中參數(shù)的名稱以匹配類A構(gòu)造函數(shù)中的參數(shù)名稱:
class A(var a: Int)
class B(a: Int) extends A(a) {
def inc(value: Int) { this.a += value }
}
Scala編譯器輸出:
$scala construct.scala
construct.scala:3: error: reassignment to val
def inc(value: Int) { this.a += value }
^
one error found
Scala抱怨,因?yàn)锽類現(xiàn)在必須擁有一個(gè)私有的只讀屬性,因?yàn)樗昧薸nc.將B(a:Int)更改為B(var a:Int)會(huì)生成不同的編譯器錯(cuò)誤:
construct.scala:2: error: error overriding variable a in class A of type Int;
variable a needs `override' modifier
class B(var a: Int) extends A(a) {
^
one error found
添加覆蓋也無(wú)濟(jì)于事:
construct.scala:2: error: error overriding variable a in class A of type Int;
variable a cannot override a mutable variable
class B(override var a: Int) extends A(a) {
^
one error found
如何在B的主構(gòu)造函數(shù)中的參數(shù)中使用與基類A的主構(gòu)造函數(shù)中定義的屬性相同的名稱?
總結(jié)
以上是生活随笔為你收集整理的scala 主构造函数_在Scala中,如何在类的主构造函数中定义局部参数?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: 底特律变人怎么存档 真免费玩《底特律
- 下一篇: 宝宝巴士如何设置声音
