Welcome to CodeYourCraft's Kotlin Default Arguments lesson! In this comprehensive guide, we'll explore how to use default arguments in Kotlin functions, making your code more flexible and easy to manage.
Default arguments are values assigned to function parameters, allowing them to have predefined values if no explicit argument is provided when the function is called. This feature makes function calls more versatile and reduces the need for multiple overloaded functions.
Default arguments help in:
Let's create a simple function with a default argument:
fun greet(name: String = "User") {
println("Hello, $name!")
}In this example, the name parameter has a default value of "User". If you call the function without providing a name:
greet()The output will be:
Hello, User!
However, if you provide a name while calling the function:
greet("Alice")The output will be:
Hello, Alice!
You can change the default value of a parameter at any point in the function declaration, but keep in mind that changing the default value may affect existing function calls with the old default value.
Let's create a function that accepts a default range of numbers:
fun printNumbers(start: Int = 1, end: Int = 10, step: Int = 1) {
for (i in start..end step step) {
println(i)
}
}You can call this function with different arguments:
printNumbers() // prints numbers from 1 to 10
printNumbers(5) // prints numbers from 5 to 10
printNumbers(start = 15, end = 20) // prints numbers from 15 to 20What happens when you call the `greet` function without providing an argument?
Default arguments in Kotlin offer a powerful way to make your functions more versatile and user-friendly. By providing reasonable default values, you simplify function calls and reduce the need for multiple function overloads. Happy coding! 🚀
Stay tuned for more in-depth lessons on Kotlin at CodeYourCraft! 🌟