I create a Kotlin-class with a class attribute, which I want to initialize in the constructor:
public class TestClass {
private var context : Context? = nul
I had a similar problem where I didn't want to hold onto the object after construction. Using lazy
or lateinit
resulted in inefficient bytecode so after some research I settled on this approach and returned to post the answer in case it helps:
class TestClass(context: Context) {
private val homeDescription: String
init {
homeDescription = context.getString(R.string.abc_action_bar_home_description)
}
fun doSomeVoodoo() {
val text : String = homeDescription
}
}
alternatively, the above can be further simplified into:
class TestClass(context: Context) {
private val homeDescription: String = context.getString(R.string.abc_action_bar_home_description)
fun doSomeVoodoo() {
val text : String = homeDescription
}
}
And the decompiled java version of this feels a bit more acceptable than the other approaches and no reference to the context is held after construction:
public final class TestClass {
private final String homeDescription;
public final void doSomeVoodoo() {
String text = this.homeDescription;
}
public TestClass(@NotNull Context context) {
Intrinsics.checkParameterIsNotNull(context, "context");
super();
String var10001 = context.getString(2131296256);
Intrinsics.checkExpressionValueIsNotNull(var10001, "context.getString(R.stri…ion_bar_home_description)");
this.homeDescription = var10001;
}
}