sreich
08/15/2022, 5:49 PMephemient
08/15/2022, 5:54 PMclass Foo {
static {
System.out.println(foo);
}
static int foo = 0;
is disallowedephemient
08/15/2022, 5:55 PMclass Foo {
int bar = foo + 1;
int foo = 0;
ephemient
08/15/2022, 5:55 PMinit
blocks, so perhaps that makes it less obvioussreich
08/15/2022, 6:04 PMsreich
08/15/2022, 6:04 PMVampire
08/15/2022, 7:16 PMJava doesn't allow you to add arbitraryThat's wrong. Java has the same, it just has no keyword. It just looks like a top-level (within the class body) block statement. But it is the same meaning as an init block in Kotlin. It is copied into all constructors. It is for example the only way to do something in the constructor of an anonymous class. The example from above adapted would beblocks, so perhaps that makes it less obviousinit
class Foo {
{
System.out.println(foo);
}
int foo = 0;
}
and would also not compile with error "Illegal forward reference".
Here is the specification of which forward references are illegal in Java: https://docs.oracle.com/javase/specs/jls/se18/html/jls-8.html#jls-8.3.3
but init {} is not static, correct?Correct, it is like in Java an initialization block
that is just the primary ctorNeither in Java, nor in Kotlin, it is part of all constructors. You can in such a way define things that should be done in all constructors even if not all constructors delegate to the same one in the end or similar.
i guess the equivalent for many cases would just be having it in Foo() {}Only if it is the sole constructor.
ephemient
08/15/2022, 7:43 PMstatic
. they get compiled into the <init>
methods, same in bothsreich
08/15/2022, 7:43 PM