Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set lateinit for a int var in Kotlin? [duplicate]

Tags:

android

kotlin

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
    }
}
like image 378
HelloCW Avatar asked Apr 01 '18 01:04

HelloCW


People also ask

How do I declare a Lateinit variable in Kotlin?

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.

How do you use Lateinit var Kotlin?

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.

How do I know my Lateinit VAR is initialized in Kotlin?

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.

How does Kotlin define Lateinit?

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.


1 Answers

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)

like image 103
Androiderson Avatar answered Oct 19 '22 00:10

Androiderson