Kotlin: Initialize class attribute in constructor

前端 未结 3 656
抹茶落季
抹茶落季 2021-02-12 11:15

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         


        
3条回答
  •  死守一世寂寞
    2021-02-12 12:04

    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:

    Solution

    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
        }
    }
    

    Decompiled Bytecode

    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;
        }
    }
    

提交回复
热议问题