Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Property must be initialized or be abstract" in init block when throwing an exception

Tags:

kotlin

Why does kotlin report Property must be initialized or be abstract. The object construction is never finished, so it should not matter whether a is initialized or not. Could a case be demonstrated where this would be a problem?

class Foo {
    private val a: Int

    init {
        a = 42
        throw Exception()
    }
}

fun main() {
    Foo()
}

kotlin playground


However these work just fine

fun bar() {
    throw Exception()
}

class Foo {
    private val a: Int

    init {
        a = 42
        bar()
    }
}

fun main() {
    Foo()
}

kotlin playground

class Foo {
    private val a: Int = throw Exception()
}

fun main() {
    Foo()
}

kotlin playground


Similar java code works as expected:

public class Test {
    private static class Foo {
        private final int a;

        public Foo() throws Exception {
            a = 42;
            throw new Exception();
        }
    }

     public static void main(String []args) throws Exception {
         new Foo();
     }
}

like image 816
Watu Avatar asked Jan 28 '26 22:01

Watu


1 Answers

Similar java code works as expected:

Java initializes fields to 0 (or null/false depending on type) by default. You can see it e.g. by printing a's value before the a = 42 line.

Kotlin doesn't, because this implicit initialization makes it too easy to forget to initialize a property and doesn't provide much benefit. So it requires you to initialize all properties which have backing fields.

like image 156
Alexey Romanov Avatar answered Jan 30 '26 23:01

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!