Search code examples
constructorkotlinclass-attribute

Kotlin: Initialize class attribute in constructor


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

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 "?".

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

Solution

  • If the only thing you are doing in the constructor is an assignment, then you could use the Primary Constructor with a private Property.

    e.g:

    public class TestClass(private val context: Context) {
    
      public fun doSomeVoodoo() {
         val text = context.getString(R.string.abc_...)
      }
    }