What are default arguments in Kotlin?

Overview

We don’t explicitly need to state the arguments when calling a function in Kotlin. Instead, we can use default arguments. In other words, passing a parameter while calling a function is optional in Kotlin. There are three cases of how arguments may be stated while calling a function. Let’s look at each case in detail.

Case 1: All arguments passed

If we pass all the arguments while calling a function, the default arguments are overwritten and not used. Let’s look at this in the code example below:

// Function Definition
fun person (name: String = "Mike", age: Int = 22) {
print("My name is ${name} and I am ${age} years old")
}
fun main(args: Array<String>) {
var name = "Anna"
var age = 10
// Function Call
person(name,age)
}

Explanation

  • Line 2: We declare a function named person that takes two parameters, name and age. These two parameters have been assigned default values.

  • Line 10: We call the function with new values of both the parameters.

When the code is executed, we see that the default arguments get overwritten.

Case 2: Partial arguments passed

If we pass only some arguments while calling a function, the passed arguments will overwrite the default arguments. For arguments we don’t pass, the default arguments will be used.

Let’s take a look at this case in the code example below:

// Function Definition
fun person (name: String = "Mike", age: Int = 22) {
print("My name is ${name} and I am ${age} years old")
}
fun main(args: Array<String>) {
var name = "Anna"
// Function Call
person(name)
}

Explanation

  • Line 2: We declare a function named person that takes in two parameters, name and age. These two parameters have been assigned default values.

  • Line 9: We call the function with a new value of name, but we don’t pass the age parameter in the function call.

As seen in the output, the value of name gets updated while the default value for age is used.

Case 3: No arguments passed

If we don’t pass any arguments while calling the function, the default arguments in the function definition are used.

Let’s take a look at this case in the code example below:

// Function Definition
fun person (name: String = "Mike", age: Int = 22) {
print("My name is ${name} and I am ${age} years old")
}
fun main(args: Array<String>) {
// Function Call
person()
}

Explanation

  • Line 2: We declare a function named person that takes in two parameters, name and age. These two parameters have been assigned default values.

  • Line 8: We call the function without giving it any arguments.

As seen in the output, the default values of name and age are used.

Copyright ©2024 Educative, Inc. All rights reserved