题目描述为什么第一个gender打印出来的是null题目来源及自己的思路我已经初试化了val gender: String = "male" ,但是貌似结果不对。相关代码object ObjectExample { def main(args: Array[String]): Unit = { val student = new Student("zhu", 18, "zz")
}
class People(val name: String, val age: Int) {
println("constructor")
println(name) val gender: String = "male"
println(gender) def this(name1: String) = { this("ci", 18)
println("subconstructor")
println(name)
}
}
class Student(name: String, age: Int, val school: String) extends People(name, age){
println("derived constructor")
println(name)
println(school) override val gender: String = "female"
println(gender)
}
}错误信息constructor
zhu
null
derived constructor
zhu
zz
female
1 回答
牧羊人nacy
TA贡献1862条经验 获得超7个赞
把class移到外面仍然是无效的。
我对这个理解就是,val类型不能被初始化两次。如果非要用重写来“初试化”两次,那么编译器就会忽略父类的初始化,而去使用子类的初始化,而此时子类的初始化并没有执行,所以只能是null。改成lazy类型就可以了,当然了,还有其他更多的方法。参考资料见Variable has been Initialized in Scala class, but what it print is null?(这个问题是我提出的)。scala官网也有解释WHY IS MY ABSTRACT OR OVERRIDDEN VAL NULL?
- 1 回答
- 0 关注
- 746 浏览
添加回答
举报
0/150
提交
取消