10

I hope to initial the private a var id later, so I use the code private lateinit var id:Int

But I get the error 'lateinit' modifier is not allowed on properties of primitive type, why? How can I fix it? Thanks!

Code A

class UIAddEditBackup: AppCompatActivity() {
    private lateinit var mContext: Context //OK
    private var isAdd: Boolean=false //OK
    private lateinit var id:Int   // I get the error

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_add_edit_backup)
        id=5
    }
}
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

18

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

With primite types you can just remove the lateinit modifier and initialize with zero (or false for booleans)

Androiderson
  • 16,865
  • 6
  • 62
  • 72