w3resource

Kotlin Function: Print a greeting message with person's name

Kotlin Function: Exercise-11 with Solution

Write a Kotlin function that takes a person's name as an argument and prints a greeting message with the name. The function should return Unit.

Sample Solution:

Kotlin Code:

fun printGreeting(name: String): Unit {
    println("Hello, $name! Welcome!")
}

fun main() {
    val personName = "Moerani Cornell"
    printGreeting(personName)
}

Sample Output:

Hello, Moerani Cornell! Welcome!

Explanation:

In the above exercise -

In the "printGreeting()" function, we receive a 'name' parameter of type String. We use string interpolation to construct the greeting message and print it using the 'println()' function. The return type Unit indicates that the function doesn't explicitly return a value.

Kotlin Editor:


Previous: Print person details with named arguments.
Next: Print numbers from 1 to n, Return Unit.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/function/kotlin-function-exercise-11.php