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
}
}
NOTE: To use a lateinit variable, your variable should use var and NOT val . Lateinit is allowed for non-primitive data types only and the variable can't be of null type. Also, lateinit variable can be declared either inside the class or it can be a top-level property.
lateinit means late initialization. If you do not want to initialize a variable in the constructor instead you want to initialize it later on and if you can guarantee the initialization before using it, then declare that variable with lateinit keyword. It will not allocate memory until initialized.
You can check if the lateinit variable has been initialized or not before using it with the help of isInitialized() method. This method will return true if the lateinit property has been initialized otherwise it will return false.
The lateinit keyword allows you to avoid initializing a property when an object is constructed. If your property is referenced before being initialized, Kotlin throws an UninitializedPropertyAccessException , so be sure to initialize your property as soon as possible.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With