0
0
Kotlinprogramming~5 mins

Unit type as void equivalent in Kotlin

Choose your learning style9 modes available
Introduction

The Unit type in Kotlin is used when a function does not return any meaningful value, similar to void in other languages.

When you want a function to perform an action but not return any result.
When you need to explicitly specify that a function returns no value.
When working with higher-order functions that expect a return type but you don't want to return anything.
When you want to make your code clearer by showing that no value is returned.
Syntax
Kotlin
fun functionName(): Unit {
    // function body
}

In Kotlin, Unit is a type with only one value, also called Unit.

You can omit : Unit because it is the default return type for functions without a return value.

Examples
This function explicitly returns Unit, meaning it returns no meaningful value.
Kotlin
fun printMessage(): Unit {
    println("Hello!")
}
This function omits : Unit but still returns Unit implicitly.
Kotlin
fun printMessage() {
    println("Hello!")
}
The println function returns Unit, so you can assign it to a variable of type Unit.
Kotlin
val result: Unit = println("Hi")
Sample Program

This program defines a function greet that returns Unit and prints a welcome message. The main function calls greet.

Kotlin
fun greet(): Unit {
    println("Welcome to Kotlin!")
}

fun main() {
    greet()
}
OutputSuccess
Important Notes

Unit is a real type in Kotlin, unlike void in Java which is just a keyword.

You can use Unit as a type argument in generics when needed.

Summary

Unit means a function returns no meaningful value.

You can omit : Unit because it is the default.

Unit is Kotlin's version of void but is an actual type.