0
0
Kotlinprogramming~20 mins

Creating instances without new keyword in Kotlin - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin Instance Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Kotlin object instantiation without 'new'
What is the output of this Kotlin code that creates an instance without using the 'new' keyword?
Kotlin
class Person(val name: String) {
    fun greet() = "Hello, $name!"
}

fun main() {
    val p = Person("Anna")
    println(p.greet())
}
AHello, Anna!
BHello, null!
CCompilation error: 'new' keyword required
DRuntime error: Uninitialized property
Attempts:
2 left
💡 Hint
In Kotlin, you create instances by calling the class name like a function.
Predict Output
intermediate
2:00remaining
Creating data class instance without 'new' keyword
What will be the output of this Kotlin code snippet?
Kotlin
data class Point(val x: Int, val y: Int)

fun main() {
    val p = Point(5, 10)
    println("x=${p.x}, y=${p.y}")
}
Ax=0, y=0
Bx=5, y=10
CCompilation error: Missing 'new' keyword
DRuntime error: Uninitialized properties
Attempts:
2 left
💡 Hint
Data classes are instantiated like normal classes in Kotlin.
🔧 Debug
advanced
2:00remaining
Why does this Kotlin code fail to compile?
Identify the reason this Kotlin code does not compile.
Kotlin
class Animal(val type: String)

fun main() {
    val a = new Animal("Dog")
    println(a.type)
}
AThe class Animal is missing a constructor
BThe println statement is incorrect
CThe property 'type' is not initialized
DKotlin does not use the 'new' keyword to create instances
Attempts:
2 left
💡 Hint
Check how Kotlin creates instances compared to Java.
🧠 Conceptual
advanced
2:00remaining
How does Kotlin create instances without 'new'?
Which statement best explains how Kotlin creates instances without using the 'new' keyword?
AKotlin requires a factory method to create instances
BKotlin uses a hidden 'new' keyword that is not visible in code
CKotlin calls the constructor directly as a function without requiring 'new'
DKotlin uses reflection to create instances at runtime
Attempts:
2 left
💡 Hint
Think about how you write code to create objects in Kotlin.
Predict Output
expert
2:30remaining
Output of Kotlin companion object instance creation
What is the output of this Kotlin code that creates an instance using a companion object without 'new'?
Kotlin
class Logger private constructor(val level: String) {
    companion object {
        fun create(level: String) = Logger(level)
    }
}

fun main() {
    val log = Logger.create("DEBUG")
    println(log.level)
}
ADEBUG
BCompilation error: private constructor inaccessible
Cnull
DRuntime error: Cannot access companion object
Attempts:
2 left
💡 Hint
Companion objects can create instances even with private constructors.