Summary - Functions
- Kotlin course
- Beginner
- Lesson 76/116
- 5 min
Combine expression body, default and named arguments to write a math helper.
Summary: expression body, default and named together
In this summary you will combine the expression body (=), a default parameter and named arguments. The one-line fun greet(name: String, msg: String = "Hello") = println("$msg $name") is both short and flexible.
fun greet(name: String, msg: String = "Hello") =
println("$msg $name")
greet("Ava") // Hello Ava
greet(name = "Ava", msg = "Hi") // Hi AvaThese three features together provide both short writing and flexibility on the caller side; the usage forms of the function fold into one definition.
Practice Expression body + default + named call
Define fun greet(name: String, msg: String = "Hello") = println("$msg $name") (expression body). From main call it with a named argument: greet(name = "Ava").
Starter code
fun main() {
// Call greet with name = "Ava"
}
// Define greet with an expression body: msg default "Hello"
// Body returns println("$msg $name") (Unit)Sample solution
fun main() {
greet(name = "Ava")
}
fun greet(name: String, msg: String = "Hello") = println("$msg $name")Expected output
Hello Ava
Practice Expression body + default for add
Define fun add(a: Int, b: Int = 0): Int = a + b (expression body). From main print the result with println(add(5)).
Starter code
fun main() {
// Print the add(5) call with println
}
// Define add with an expression body: b default 0, returns a + bSample solution
fun main() {
println(add(5))
}
fun add(a: Int, b: Int = 0): Int = a + bExpected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which definition combines all three features?
- fun greet(name, msg) { println("$msg $name") }; greet("Ava")
- fun greet(name: String = "Ava"): String = "Hi"
- fun greet(name: String) = println(name); greet(name = "Ava")
- fun greet(name: String, msg: String = "Hi") = println("$msg $name"); greet(name = "Ava") Correct answer
Explanation: Expression body (=), default msg and named call are all present.
2 Fill in the blank: named argument
greet(name ____ "Ava", msg = "Hi")
greet(name = "Ava", msg = "Hi")
Explanation: greet(name = "Ava", msg = "Hi") is a named call.