0
0
Kotlinprogramming~15 mins

Parameters with default values in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Parameters with Default Values in Kotlin
📖 Scenario: You are creating a simple greeting function for a friendly chatbot. Sometimes the chatbot knows the user's name, and sometimes it doesn't. You want the chatbot to greet the user by name if given, or use a general greeting if no name is provided.
🎯 Goal: Build a Kotlin function called greet that uses a parameter with a default value. This function will print a greeting message using the name if provided, or a default greeting if no name is given.
📋 What You'll Learn
Create a function named greet with a parameter name of type String that has a default value.
Set the default value of name to "Guest".
Inside the function, print a greeting message using the name parameter.
Call the greet function twice: once without any argument, and once with the argument "Alice".
💡 Why This Matters
🌍 Real World
Functions with default parameters are common in apps and programs to provide flexible behavior without forcing users to always give all details.
💼 Career
Understanding default parameters is important for writing clean, reusable code in Kotlin, which is widely used for Android app development and backend services.
Progress0 / 4 steps
1
Create the greet function with a name parameter
Write a Kotlin function called greet that has one parameter named name of type String. Set the default value of name to "Guest". Inside the function, write a print statement that prints "Hello, $name!" using string interpolation with println.
Kotlin
Need a hint?

Use fun greet(name: String = "Guest") to create the function with a default parameter. Use println("Hello, $name!") to print the greeting.

2
Call greet without an argument
Call the greet function without passing any argument to use the default name.
Kotlin
Need a hint?

Just write greet() to call the function without any argument.

3
Call greet with the argument "Alice"
Add a call to the greet function passing the argument "Alice" to greet Alice by name.
Kotlin
Need a hint?

Call the function with greet("Alice") to greet Alice.

4
Print the greetings
Run the program so it prints the greetings for the default name and for "Alice".
Kotlin
Need a hint?

Just run the program. It should print two greetings: one for the default name and one for Alice.