0
0
Kotlinprogramming~5 mins

Unit type as void equivalent in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the Kotlin equivalent of 'void' in Java?
In Kotlin, the equivalent of Java's 'void' is the 'Unit' type. It represents a function that returns no meaningful value.
Click to reveal answer
beginner
What value does a Kotlin function with return type 'Unit' return?
A Kotlin function with return type 'Unit' returns a single instance called 'Unit'. It is similar to returning nothing but is an actual object.
Click to reveal answer
beginner
Can you omit the 'Unit' return type in Kotlin functions?
Yes, if a Kotlin function returns 'Unit', you can omit the return type declaration. The compiler infers it automatically.
Click to reveal answer
intermediate
How does Kotlin's 'Unit' type help in writing cleaner code compared to 'void'?
Since 'Unit' is a real type with a value, it can be used in generics and expressions, unlike 'void' which is just a keyword. This makes Kotlin code more consistent and expressive.
Click to reveal answer
beginner
Show a simple Kotlin function that returns 'Unit' explicitly.
fun greet(): Unit { println("Hello!") } This function returns 'Unit' explicitly, meaning it returns no meaningful value but completes its action.
Click to reveal answer
What does the Kotlin 'Unit' type represent?
AA function that returns null
BA function that returns an integer
CA function that returns no meaningful value
DA function that throws an exception
Can you omit the 'Unit' return type in Kotlin function declarations?
AYes, the compiler infers it automatically
BOnly if the function is private
CNo, it must always be declared
DOnly if the function is inline
Which of these is a valid Kotlin function signature for a function returning 'Unit'?
Afun printMessage(): Int
Bfun printMessage(): Unit
Cfun printMessage(): String
Dfun printMessage(): null
What is the value returned by a Kotlin function with return type 'Unit'?
Anull
BNo value, it throws an error
C0
DUnit instance
Why is Kotlin's 'Unit' type more flexible than Java's 'void'?
ABecause 'Unit' is a real type and can be used in generics
BBecause 'Unit' can hold multiple values
CBecause 'Unit' is a keyword like 'void'
DBecause 'Unit' can be null
Explain the role of the 'Unit' type in Kotlin and how it compares to 'void' in other languages.
Think about what happens when a function doesn't return anything.
You got /4 concepts.
    Write a Kotlin function that prints a message and explicitly returns 'Unit'.
    Use fun functionName(): Unit { ... }
    You got /3 concepts.