In code like the below, Kotlin complains that the ...
# getting-started
j
In code like the below, Kotlin complains that the fields aren't initialized, even though if I copy the code from
updateFields
into the second constructor it does. Is there a way I can get Kotlin to know the fields are always initialized, without duplicating the code between
updateFields
and the constructor?
Copy code
class DemoClass
{
    var field1: Int
        private set
    var field2: Int
        private set

    constructor(f1: Int, f2: Int) {
        field1 = f1
        field2 = f2
    }

    constructor(basef: Int) {
        updateFields(basef)
    }

    fun updateFields(basef: Int) {
        field1 = basef * 2
        field2 = basef + 2
    }
}
K 1
l
You can declare a variable as 'lateinit var' to promise the compiler you will initialize it.
h
the easiest way to solve this problem is to initialized the number
Copy code
class DemoClass
{
    var field1: Int = 0
        private set
    var field2: Int = 0
        private set

    constructor(f1: Int, f2: Int) {
        field1 = f1
        field2 = f2
    }

    constructor(basef: Int) {
        updateFields(basef)
    }

    fun updateFields(basef: Int) {
        field1 = basef * 2
        field2 = basef + 2
    }
}
@Landry Norris lateinit may not work for primitive types 😞
j
So initialize it for primitive or nullable, lateinit for non-nullable objects?
🙌 1
l
Doesn't it force the primitive to be boxed? Slight performance hit, but should work. Guess it doesn't do this.
j
It still seems like the compiler should be able to figure that out, though.
As long as the method called isn't open.
🙌 1
h
Let me know if you find a better way 🙂
e
Copy code
class DemoClass(field1: Int, field2: Int) {
    var field1 = field1
        private set
    var field2 = field2
        private set

    constructor(basef: Int) : this(
        field1 = basef * 2,
        field2 = basef + 2,
    )
}
j
@ephemient: This doesn't solve the problem of duplicating the code between the constructor and the update method (the idea is that class also allows the
updateFields
method to be called later to change the values).
e
then
Copy code
class DemoClass(field1: Int, field2: Int) {
    var field1 = field1
        private set
    var field2 = field2
        private set

    constructor(basef: Int) : this(0, 0) {
        updateFields(basef)
    }
}