Class Declarations & Members
The mechanics of declaring a class: constructors and init blocks, properties and their backing fields, custom accessors, visibility, and nesting. Interviewers probe here because initialization order and backing-field rules produce real bugs.
part ofKotlinoverview, primer and where to startread it →on this pageshowhide
explore
- Primary Constructor5 questions
- Secondary Constructors & this() Delegation5 questions
- init Blocks & Initialization Order5 questions
- Properties & Backing Fields5 questions
- Custom Getters & Setters5 questions
- Visibility Modifiers & internal6 questions
- Nested vs inner Classes5 questions
questions
page 2 of 2How do you control the visibility of a primary constructor and of a property's setter independently in Kotlin?
basics
~20 sPut the visibility keyword before the constructor keyword to restrict a primary constructor, e.g. class C private constructor(). For a property, you can give the setter its own visibility like 'var x: Int = 0; private set' so reads are public but writes are private.
What exactly is a 'module' for the internal modifier, and when would you choose internal over public or private?
basics
~20 sinternal means visible everywhere within the same compilation module. A module is a set of files compiled together — like one Gradle source set or IntelliJ module. Use internal to expose things across your module but hide them from outside consumers.
How does `init` block timing relate to companion-object initialization and to secondary constructors with `this(...)` delegation?
basics
~20 sThe companion object initializes once when the class is first loaded, before any instance exists. init blocks run for each instance. A secondary constructor first delegates to the primary (running init), then runs its own body.
How do secondary constructors behave when a class has no primary constructor, including delegation to a superclass?
basics
~10 sWithout a primary constructor, a secondary constructor can fully initialize the object itself and may call the base class with super(...). There is no this(...) requirement because there is no primary to delegate to.
What does the compiler actually generate for nested vs inner classes, and how should that inform your default choice when designing an API?
basics
~20 sA nested class compiles to a standalone (static-like) class with no link to the outer. An inner class compiles to a class with a hidden field pointing at the outer object. Default to nested and only add inner when you truly need that link.
How do Kotlin's visibility modifiers map onto JVM bytecode access flags, and why does that matter?
basics
~20 sKotlin enforces visibility at compile time, then compiles to JVM access flags: public stays public, protected stays protected, but private members are sometimes public in bytecode, and internal becomes public with a mangled name. So Java can sometimes reach what Kotlin hides.
showing 31–36 of 36