0
0
Kotlinprogramming~5 mins

Primary constructor and init blocks in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a primary constructor in Kotlin?
A primary constructor is a concise way to declare and initialize class properties directly in the class header.
Click to reveal answer
beginner
What is the purpose of an init block in Kotlin?
An init block contains initialization code that runs when an instance of the class is created, allowing extra setup beyond property declarations.
Click to reveal answer
intermediate
How do primary constructor parameters relate to properties?
Parameters in the primary constructor can be used to initialize properties by prefixing them with val or var, making them class properties.
Click to reveal answer
intermediate
Can a Kotlin class have multiple init blocks? What happens when it does?
Yes, a class can have multiple init blocks. They run in the order they appear in the class, each executing during object creation.
Click to reveal answer
advanced
Explain the order of execution when creating an object with a primary constructor and init blocks.
First, the primary constructor parameters are passed. Then, property initializers run. After that, all init blocks execute in order. Finally, the object is fully created.
Click to reveal answer
What keyword do you use to declare a property in the primary constructor?
Aclass
Bfun
Cval or var
Dinit
When is the code inside an init block executed?
AWhen the program ends
BWhen the class is compiled
CWhen a method is called
DWhen an object of the class is created
Can you have multiple init blocks in a Kotlin class?
AYes, and they run in the order they appear
BNo, only one init block is allowed
CYes, but only the first one runs
DNo, init blocks are not allowed
What happens if you declare a primary constructor parameter without val or var?
AIt is just a parameter and not a property
BIt becomes a global variable
CIt causes a compile error
DIt becomes a property automatically
Which of these is the correct order during object creation?
AProperty initializers → primary constructor → init blocks
BPrimary constructor → property initializers → init blocks
CInit blocks → primary constructor → property initializers
DPrimary constructor → init blocks → property initializers
Describe how you use a primary constructor and init blocks together to initialize a Kotlin class.
Think about how constructor parameters and init blocks complement each other.
You got /4 concepts.
    Explain why you might use multiple init blocks in a Kotlin class.
    Consider how splitting initialization into parts can help keep code clear.
    You got /4 concepts.