我创建了一个科特林级与类属性,这是我想在构造函数初始化:科特林:初始化类属性在构造函数中
public class TestClass {
private var context : Context? = null // Nullable attribute
public constructor(context : Context) {
this.context = context
}
public fun doSomeVoodoo() {
val text : String = context!!.getString(R.string.abc_action_bar_home_description)
}
}
不幸的是我已经与“申报属性为可为空? “签名,但该属性将在构造函数中初始化。将该属性声明为Nullable属性使得始终需要强制使用“!!”的NonNull值或用“?”提供空值检查。
有什么办法避免这种情况,如果类属性将在构造函数初始化?我想明白这样一个解决方案:
public class TestClass {
private var context : Context // Non-Nullable attribute
public constructor(context : Context) {
this.context = context
}
public fun doSomeVoodoo() {
val text : String = context.getString(R.string.abc_action_bar_home_description)
}
}
第二个例子正在与科特林0.12.213。你使用什么Kotlin版本? – D3xter
它的工作原理。我已经使用0.12.613。但我认为,我做错了什么。抱歉! – Christopher
有更多的案例可用,我添加了一个完整覆盖的答案。 –