CodeBlanks Logo Icon CodeBlanks

Summary - Functions

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 Ava

These 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

Main.kt
fun main() {
    // Call greet with name = "Ava"
}

// Define greet with an expression body: msg default "Hello"
// Body returns println("$msg $name") (Unit)

Sample solution

Main.kt
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

Main.kt
fun main() {
    // Print the add(5) call with println
}

// Define add with an expression body: b default 0, returns a + b

Sample solution

Main.kt
fun main() {
    println(add(5))
}

fun add(a: Int, b: Int = 0): Int = a + b

Expected 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

Question
greet(name ____ "Ava", msg = "Hi")
Answer
greet(name = "Ava", msg = "Hi")

Explanation: greet(name = "Ava", msg = "Hi") is a named call.

All lessons in Beginner