在我看来,这两类人的行为似乎是一样的:
class A constructor(ii_: Int) {
var ii = 0
var xx = 0.0F
var msg = ""
init {
ii = ii_
xx = ii + 42.0F
msg = "The value of ii is $ii and the value of xx is $xx"
}
fun display() {
print("A.display() $ii, $xx\n")
print("A.display() $msg\n")
}
}
class C {
var ii = 0
var xx = 0.0F
var msg = ""
constructor(ii_: Int) {
ii = ii_
xx = ii + 42.0F
msg = "The value of ii is $ii and the value of xx is $xx"
}
fun display() {
print("C.display() $ii, $xx\n")
print("C.display() $msg\n")
}
}如果我没有一个以上的构造函数,那么使用主构造函数的版本有什么好处吗?
是否有一个理论上的原因,我没有看到主要的ctor + init块方案?
带有init块的主构造函数版本似乎是巴洛克式的,这让我认为有更深层次的原因,但我看不到它。
我知道我的A类不需要构造函数关键字。这不是我要问的,请不要告诉我我不需要它。
发布于 2020-12-21 12:26:21
init块更像属性初始化函数,而不是构造函数。(如果您了解这个问题,它们与Java的实例初始值基本相同;参见这个问题和这一讨论。)主要问题如下:
init块;它们都按照顺序(以及属性初始化器表达式)运行,您可以使用它们来初始化属性,为了清晰起见,可以将它们放在属性旁边。object表达式和声明中使用(它们最初被引入到Java中,相当于匿名类)。https://stackoverflow.com/questions/65388206
复制相似问题