Lateinit primitive types

I am sure this has been asked before, why no lateinit primitive types?
However, I am just confused with the answer that lateinit primitives are technically impossible

From what I know the null value is used as uninitialized markers for object types underlyingly.
Why can’t we do the same with primitives using boxed primitives (Integer instead of int)?

We are able to do Int? but not lateinit var: Int
why?

1 Like

I think the fundamental reason for this not to work is that lateinit doesn’t change the type.

With this suggestion - which would work - then adding lateinit would change the type of the underlying object.

2 Likes

i mean adding the question mark to Int also changes its type from primitive to boxed primitive too, right?

1 Like

Yes, but that’s a direct change to the type, while lateinit is “further away” geographically from the type. I agree that it should just be allowed, but I can see why it isn’t a thing yet.
There is a bug for it on Youtrack: https://youtrack.jetbrains.com/issue/KT-15284

1 Like

Anyway, for now you can use Delegates.notNull() for a very similar effect:

var num by Delegates.notNull<Int>()

// println(num) // IllegalStateException
num = 8
println(num) // 8
1 Like

Currently (version 1.9.24), instead of lateinit primitive property I have to declare initialized property:

class Example {
    lateinit var property1: String

    var property2: Boolean = false

    lateinit var property3: StringBuilder

    var property4: Int = 0
}

- this looks quite ugly near lateinit object properties. Also, I have to declare some random value.

Why don’t you allow lateinit primitive property with similar initialization for backed field, ignoring scenario where property is not initialized to throw exception

So if there’s no exception, what do you get when you try to read it? Some random value?

Yes, some random value.

Because:

  1. In good case scenario (if I set value later) it doesn’t matter
  2. In bad case scenario the behaviour is the same as in my current code:
var property2: Boolean = false

- where I get “random” value. I wouldn’t be able to determine if property was initialized or not