scala 主构造函数_在Scala中,如何在类的主构造函数中定义局部参数?

在Scala中,如何在不是数据成员的类的主构造函数中定义局部参数,例如,仅用于初始化基类中的数据成员?

例如,在下面的代码中,如何在B类的主构造函数中正确定义参数b,以便它只生成临时本地参数而不是数据成员?

class A(var a: Int)

class B(?b?) extends A(b)

Randall,你的答案解释了当我引入一个增加属性a的方法inc时Scala编译器抱怨的原因,同时也改变了B类构造函数中参数的名称以匹配类A构造函数中的参数名称:

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抱怨,因为B类现在必须拥有一个私有的只读属性,因为它引用了inc.将B(a:Int)更改为B(var a:Int)会生成不同的编译器错误:

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

添加覆盖也无济于事:

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的主构造函数中的参数中使用与基类A的主构造函数中定义的属性相同的名称?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值