w3resource

Kotlin Function: Print message without return


Write a Kotlin function that prints a message and does not return anything.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Unit Type.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Print the Message.
  • No Return Value.
  • Call the Function.
  • Test with Different Messages.
  • Common Errors to Avoid:
    • Forgetting function parameters.
    • Misplacing println().
    • Unnecessarily adding a return statement.

Sample Solution:

Kotlin Code:

fun printMessage(message: String) {
    println(message)
}
fun main() {
    printMessage("Hello, world!")
}

Sample Output:

Hello, world!

Explanation:

The "printMessage()" function takes a parameter message of type String. Inside the function, it prints the message using the println function.

In the main function, we call the "printMessage()" function and provide the message "Hello, world!" as an argument. The function prints the message to the console.

Since the "printMessage()" function does not return any value (unit-returning function), its return type is Unit, which is the default return type for functions that do not specify a return type explicitly.

Kotlin Editor:


Previous: Check if a string is a palindrome.
Next: Calculate area of rectangle with default Values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.