0
fun main() {
    val lateData = LateData()
    with(lateData) {
        lateinitNumber = 10
        nullableNumber.printLog()
        lateinitNumber.printLog()
    }
}
class LateData {
    var nullableNumber: Int? = null
    lateinit var lateinitNumber: Int
}

I was intended to use lateinit keyword, but lateinit in LateData class shows red underline. how can I fix this?

JunJaBoy
  • 25
  • 4
  • 2
    You cannot have lateinit on a primitive type. According to the [Kotlin doc](https://kotlinlang.org/docs/properties.html#late-initialized-properties-and-variables), "*The type of the property or variable must be non-null, and it must not be a primitive type.*" – Madhu Bhat Sep 09 '22 at 14:34
  • Aside from that, `lateinit` should only be used for classes where your code will never handle instances between initialization time and when they have been set up through some lifecycle function. These are typically classes from platform frameworks like Android or dependency injection frameworks, where there is some initialization function with a name like `create` or `onCreate`, which is called at the first time your code base has access to the instance. If that's not what you're using, it is far more robust to use a nullable property type instead of `lateinit`. – Tenfour04 Sep 09 '22 at 15:08
  • 1
    Your IDE should show you what the problem is, e.g. when you mouse over the red underline, or if you click on the error counts at the top-right of the pane, or in the build output. – gidds Sep 09 '22 at 15:51

0 Answers0