When are `object`s initialized? Is it directly at ...
# getting-started
l
When are `object`s initialized? Is it directly at program start / JVM start (if on JVM)?
h
First access
thank you color 1
l
Although for `companion object`s it seems to be "whenever JVM static initializer runs": https://kotlinlang.org/docs/object-declarations.html#behavior-difference-between-object-declarations-and-expressions
c
Objects on the whole are sugar for this pattern:
Copy code
class Foo {
  public static final Foo INSTANCE = new Foo();
}
So they get instantiated when the static initializer runs, which is on the first time the class is accessed
l
Thank you!
k
So they get instantiated when the static initializer runs, which is on the first time the file is accessed
No, not the first time the file is accessed but the first time the object is accessed.
thank you color 1
c
Whoops, I was thinking in Java and forgot that top-level stuff exists. That's what I meant, thanks for clarifying
k
Even in Java, you can have multiple class definitions at the top level in the same file (as long as they're package-private, not public) and then only the accessed class(es) would get initialized.
👍 1