Default and Named Arguments Kotlin
In Kotlin, you can provide default values for function parameters, so that the caller can omit them if they want to use the default value. This is useful when you have a function with optional parameters, or when you want to provide sensible default values for commonly used parameters. Here's an example:
fun greet(name: String = "World") { println("Hello, $name!") } fun main() { greet() greet("Alice") }
In this example, we have defined a function called greet
that takes an optional input parameter name
of type String
. If the name
parameter is not provided, the function uses the default value of "World".
In the main
function, we call the greet
function twice: once without any input parameters, and once with the input parameter "Alice". When we call the function without any input parameters, it uses the default value of "World" for the name
parameter, and prints "Hello, World!" to the console. When we call the function with the input parameter "Alice", it uses the value of "Alice" for the name
parameter, and prints "Hello, Alice!" to the console.
You can also use named arguments in Kotlin, which allow you to specify the name of the parameter along with its value. This can be useful when you want to provide input parameters out of order, or when you want to omit some of the optional parameters. Here's an example:
fun greet(name: String = "World", age: Int = 30) { println("Hello, $name! You are $age years old.") } fun main() { greet(age = 25, name = "Bob") greet(name = "Alice") }
In this example, we have defined a function called greet
that takes two optional input parameters: name
of type String
, and age
of type Int
. If the name
and age
parameters are not provided, the function uses the default values of "World" and 30, respectively.
In the main
function, we call the greet
function twice: once with the input parameters "Bob" for name
and 25 for age
, and once with the input parameter "Alice" for name
. When we call the function with the input parameters "Bob" and 25, it uses the values of "Bob" and 25 for the name
and age
parameters, respectively, and prints "Hello, Bob! You are 25 years old." to the console. When we call the function with the input parameter "Alice", it uses the value of "Alice" for the name
parameter, and the default value of 30 for the age
parameter, and prints "Hello, Alice! You are 30 years old." to the console.
Note that named arguments must always follow positional arguments, if any. Also, if you provide a value for a named parameter, you must provide values for all subsequent named parameters, or use default values for them.