0
0
Kotlinprogramming~20 mins

Unit type as void equivalent in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Unit Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin function returning Unit?
Consider the following Kotlin code. What will be printed when printResult() is called?
Kotlin
fun printResult(): Unit {
    println("Hello from Unit function")
}

fun main() {
    printResult()
}
AHello from Unit function
Bnull
CUnit
DNo output
Attempts:
2 left
💡 Hint
Remember that Unit functions can print output but do not return a value to print.
Predict Output
intermediate
2:00remaining
What is the value of variable x after this Unit function call?
Look at this Kotlin code. What is the value of x after calling val x = printMessage()?
Kotlin
fun printMessage(): Unit {
    println("Message printed")
}

fun main() {
    val x = printMessage()
    println(x)
}
ACompilation error
Bnull
CMessage printed
DUnit
Attempts:
2 left
💡 Hint
Functions returning Unit assign Unit to variables.
🔧 Debug
advanced
2:00remaining
Why does this Kotlin code cause a compilation error?
Examine the code below. Why does it fail to compile?
Kotlin
fun doSomething(): Unit {
    return 5
}

fun main() {
    doSomething()
}
ACannot return a value from a function with Unit return type
BUnit functions must return null explicitly
CMissing return statement
DThe function must return a String
Attempts:
2 left
💡 Hint
Unit means no meaningful value is returned.
🧠 Conceptual
advanced
2:00remaining
Which statement about Kotlin's Unit type is true?
Choose the correct statement about the Unit type in Kotlin.
AUnit functions must always return null explicitly
BUnit is equivalent to Java's null
CUnit is a singleton object representing no meaningful value
DUnit is a primitive type like Int or Boolean
Attempts:
2 left
💡 Hint
Think about what Unit represents in Kotlin functions.
Predict Output
expert
2:00remaining
What is the output of this Kotlin code involving Unit?
Analyze the code and select the exact output printed to the console.
Kotlin
fun foo(): Unit {
    println("Start")
    return Unit
}

fun main() {
    val result = foo()
    println(result)
}
AStart
B
Start
kotlin.Unit
C
Start
Unit
D
Start
null
Attempts:
2 left
💡 Hint
The function prints "Start" and returns Unit which prints as kotlin.Unit.