Kotlin: Initialize class attribute in constructor

前端 未结 3 651
抹茶落季
抹茶落季 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 11:47

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

提交回复
热议问题