【发布时间】:2015-09-11 15:22:02
【问题描述】:
我创建了一个带有类属性的 Kotlin 类,我想在构造函数中对其进行初始化:
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。符号,尽管属性将在构造函数中初始化。将此属性声明为 Nullable-attribute 使得始终需要使用“!!”强制 NonNull-value或使用“?”提供 Null 检查。
如果类属性将在构造函数中初始化,有什么方法可以避免这种情况?我想感谢这样的解决方案:
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)
}
}
【问题讨论】:
-
第二个例子是使用 Kotlin 0.12.213。您使用的是什么 Kotlin 版本?
-
它有效。我已经使用了 0.12.613。但我想,我做错了什么。对不起!
-
有更多案例可用,我添加了完整覆盖的答案。
标签: constructor kotlin class-attribute