0
0
Kotlinprogramming~15 mins

Unit type as void equivalent in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Unit Type as Void Equivalent in Kotlin
📖 Scenario: Imagine you are creating a simple Kotlin program that performs actions without returning any value, similar to how void works in other languages.
🎯 Goal: You will learn how to use Kotlin's Unit type as the equivalent of void by creating functions that do not return any value and calling them.
📋 What You'll Learn
Create a function with return type Unit
Create a function without explicitly specifying return type that returns Unit
Call both functions
Print messages inside the functions to show they are executed
💡 Why This Matters
🌍 Real World
Many Kotlin programs use <code>Unit</code> functions for actions like printing, logging, or updating UI where no return value is needed.
💼 Career
Understanding <code>Unit</code> helps you read and write Kotlin code clearly, especially when working with functions that perform tasks without returning data.
Progress0 / 4 steps
1
Create a function with return type Unit
Write a function called printHello that returns Unit and prints the message "Hello from printHello" inside it.
Kotlin
Need a hint?

Remember, Unit is the Kotlin equivalent of void. You can specify it explicitly as the return type.

2
Create a function without explicit return type (Unit inferred)
Write a function called printWorld that does not specify a return type but prints the message "Hello from printWorld" inside it.
Kotlin
Need a hint?

If you don't specify a return type, Kotlin assumes Unit for functions without a return value.

3
Call both functions
Call the functions printHello() and printWorld() in the main function.
Kotlin
Need a hint?

Inside main, just write the function calls on separate lines.

4
Print the output of calling the functions
Run the program and observe the printed output from calling printHello() and printWorld(). The output should show both messages.
Kotlin
Need a hint?

When you run the program, you should see both messages printed on separate lines.