gpt4 book ai didi

kotlin - "Property must be initialized or be abstract"in init block 抛出异常

转载 作者:行者123 更新时间:2023-12-02 12:24:19 25 4
gpt4 key购买 nike

为什么kotlin报Property must be initialized or be abstract。对象构造永远不会完成,所以 a 是否初始化应该无关紧要。能否举出一个案例来证明这是一个问题?

class Foo {
private val a: Int

init {
a = 42
throw Exception()
}
}

fun main() {
Foo()
}

kotlin playground


但是这些工作得很好

fun bar() {
throw Exception()
}

class Foo {
private val a: Int

init {
a = 42
bar()
}
}

fun main() {
Foo()
}

kotlin playground

class Foo {
private val a: Int = throw Exception()
}

fun main() {
Foo()
}

kotlin playground


类似的 java 代码按预期工作:

public class Test {
private static class Foo {
private final int a;

public Foo() throws Exception {
a = 42;
throw new Exception();
}
}

public static void main(String []args) throws Exception {
new Foo();
}
}

最佳答案

这个问题在下面的链接中得到了很好的回答。
Kotlin: why do I need to initialize a var with custom getter?

从本质上讲,它归结为每个“val”(属性)都有一个支持字段。如果您可以提供支持字段,则无需初始化该字段。下面是它的一个小例子。

class Foo {
private val a: Int
get() = getValue()

}

fun getValue():Int {
throw Exception()
}

fun main() {
Foo()
}

关于kotlin - "Property must be initialized or be abstract"in init block 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57067014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com