https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

sreich

08/15/2022, 5:49 PM
it appears to me that kotlin is more sensitive at the class level, at order of operations? it seems to process class files/fields vertically. I don't recall java having as many cases as this does. But for instance, a class level property being referenced by the init {} block, the property must be above. is this behavior actually different, or just something i haven't run into enough before? What is it called?
e

ephemient

08/15/2022, 5:54 PM
similar as Java,
Copy code
class Foo {
  static {
    System.out.println(foo);
  }
  static int foo = 0;
is disallowed
and for non-static, Java also rejects
Copy code
class Foo {
  int bar = foo + 1;
  int foo = 0;
Java doesn't allow you to add arbitrary
init
blocks, so perhaps that makes it less obvious
s

sreich

08/15/2022, 6:04 PM
but init {} is not static, correct? that is just the primary ctor
i guess the equivalent for many cases would just be having it in Foo() {}
v

Vampire

08/15/2022, 7:16 PM
Java doesn't allow you to add arbitrary
init
blocks, so perhaps that makes it less obvious
That'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 be
Copy code
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 ctor
Neither 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.
e

ephemient

08/15/2022, 7:43 PM
oh I forgot about those initializer blocks, I only remembered
static
. they get compiled into the
<init>
methods, same in both
s

sreich

08/15/2022, 7:43 PM
hmmm interesting. didn't know a lot of this