Kotlin:在构造函数中初始化类属性 [英] Kotlin: Initialize class attribute in constructor
问题描述
我创建一个带有class属性的Kotlin类,该属性要在构造函数中初始化:
I create a Kotlin-class with a class attribute, which I want to initialize in the constructor:
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值.或提供带有?"的空检查.
Unfortunately I have to declare the attribute as Nullable with the "?" sign, although the attribute will be initialized in the constructor. Declaring this attribute as Nullable-attribute makes it always necessary to force an NonNull-value with "!!" or to provide a Null-check with "?".
如果将在构造函数中初始化class属性,有什么办法可以避免这种情况?我想感谢这样的解决方案:
Is there any way to avoid this, if the class attribute will be initialized in the constructor? I would like to appreciate a solution like this one:
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)
}
}
推荐答案
如果您在构造函数中唯一要做的事情是赋值, 那么您可以将主构造函数与私有属性一起使用.
If the only thing you are doing in the constructor is an assignment, then you could use the Primary Constructor with a private Property.
例如:
public class TestClass(private val context: Context) {
public fun doSomeVoodoo() {
val text = context.getString(R.string.abc_...)
}
}
这篇关于Kotlin:在构造函数中初始化类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!