0

Why is it not possible to use lateinit with Boolean in Kotlin? I tried it with the other primitive data types and it works fine!

Here is the code that I want to use:

object BankAccount {
    lateinit var accountName: String
    lateinit var accountNumber: String
    lateinit var accountStatus : Boolean
}

This is what the error says:

'lateinit' modifier is not allowed on properties of primitive types

Chandresh Parmar
  • 176
  • 1
  • 10

2 Answers2

1

lateinit doesn't work with primitive or nullable types, because internally it uses null as "uninitialized" value. Since fields of primitive types can't be null, the internal lateinit mechanism can't work.

i tried it with the other primitive data types and it works fine !

You probably misread something. lateinit doesn't work with any primitive types.

Jorn
  • 20,612
  • 18
  • 79
  • 126
0

The reason you can't use lateinit with Boolean or other primitive types like Int, Long, etc., is that these types cannot be null by default. The lateinit modifier is intended for properties that are nullable by default, and it allows you to defer the initialization of such properties until later in the code. If you need to represent a nullable boolean, you can use the nullable Boolean type (Boolean?) and initialize it with null instead.

hnxtay
  • 1
  • 1