Kotlin Function: Print a greeting message with person's name
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.
Pre-Knowledge (Before you start!)
- Basic Kotlin Syntax.
- Kotlin Functions.
- Unit Type.
- String Interpolation.
- Printing Output.
Hints (Try before looking at the solution!)
- Define the Function.
- Print the Greeting.
- Call the Function.
- Test with Different Names.
- Common Errors to Avoid:
- Forgetting function parameters.
- Misplacing string interpolation syntax.
- Unnecessarily adding a return statement.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics