Lesson 7
Simplifying Kotlin Function Calls: Named Arguments and Default Values
Topic Overview

Welcome! Today's Kotlin lesson demystifies two key features: named arguments and default parameter values. They make function calls clearer and the code more maintainable.

Named Arguments in Kotlin

Named arguments enhance code readability by associating each argument with a parameter name, thereby eliminating the need to remember their order.

Imagine you're drawing a rectangle:

Kotlin
1fun drawRectangle(height: Int, width: Int, color: String) { 2 // Code here 3}

This function can be called using named parameters, providing better clarity when reading the code:

Kotlin
1drawRectangle(height = 5, color = "blue", width = 10) 2drawRectangle(height = 5, width = 10, color = "blue") 3drawRectangle(color = "blue", width = 10, height = 5)

Named arguments make function invocations self-explanatory, reducing errors and improving readability.

Default Parameter Values in Kotlin

Default parameter values assign a default value to a function parameter. They permit the skipping of parameters that aren't required for the function call.

Consider a function that greets a user:

Kotlin
1fun greetUser(name: String = "Guest") { 2 println("Hello, $name") 3}

You can call this function in three ways:

Kotlin
1greetUser() // Displays "Hello, Guest" 2greetUser("John") // Displays "Hello, John" 3greetUser(name = "Emily") // Displays "Hello, Emily"

The first function call uses the default value, as no argument is passed.

Combining Named Arguments and Default Parameter Values

The combination of both concepts brings flexibility and clarity.

Let's modify the drawRectangle function, adding a default color:

Kotlin
1fun drawRectangle(height: Int, width: Int, color: String = "Red") { 2 // Implementation 3}

You can then call this function as follows:

Kotlin
1drawRectangle(height = 20, width = 30) // color is "Red" 2drawRectangle(height = 20, color = "Blue", width = 30) // color is "Blue"
Lesson Summary and Upcoming Practice

Excellent work! We've expanded our function toolkit by learning about named arguments and default parameter values. These features simplify function calls, thereby improving your Kotlin expertise.

Now, it's time for hands-on practice tasks to solidify your understanding. The combination of learning with practice is key to mastery in coding. So, let's start coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.