scala中的预先定义

Early definitions are particularly useful for traits, which do not have normal constructor parameters. Example:
预先定义对traits特别有用(traits没有常规构造函数函数),例如:

trait Greeting {
val name: String
val msg = "How are you, "+name
}
class C extends {
val name = "Bob"
} with Greeting {
println(msg)
}


In the code above, the field name is initialized before the constructor of Greeting is called. Therefore, field msg in class Greeting is properly initialized to "How are you, Bob".
name会在Greeting构造函数调用之前初始化,最终,msg会被正确的初始化为“How are you,Bob”
If name had been initialized instead in C’s normal class body, it would be initialized after the constructor of Greeting. In that case, msg would be initialized to "How are you, <null>".
如果name在常规的C的正常class体内初始化,那么它会在Greeting构造函数中初始化,msg将会初始化为“How are you,<null>”
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值