1. Function Types and Lambda Syntax

[THEORY]

[PREDICT]

Read the code carefully before you run it.

prediction.kt
fun main() {
    var discount: (Double) -> Double = { price -> price * 0.9 }
    val noDiscount: (Double) -> Double = { price -> price }

    println(discount(100.0))
    discount = noDiscount
    println(discount(100.0))
}

discount is a var that holds a function as its value. What does the second println output after discount is reassigned?

[TASK]

A shipping company calculates shipping costs based on a package's weight and whether express shipping is requested. Write a function shippingCost(weight: Double, express: Boolean): Double. Inside it, first declare a val standardShipping of function type (Double) -> Double that calculates the shipping cost as weight * 1.5, and a var shippingFunction that initially points to standardShipping. If express is true, assign shippingFunction a new lambda that instead calculates weight * 1.5 + 10.0. At the end return shippingFunction(weight). Call shippingCost in main for weight = 4.0 once with express = false and once with express = true and print both results.

task.kt
fun shippingCost(weight: Double, express: Boolean): Double { // TODO: val standardShipping: (Double) -> Double = ... // TODO: var shippingFunction = standardShipping // TODO: if express is true, reassign shippingFunction (express shipping lambda) // TODO: return shippingFunction(weight) } fun main() { println(shippingCost(4.0, express = false)) println(shippingCost(4.0, express = true)) }

Before you get a hint: what have you tried, and where exactly are you stuck?

[COMPREHENSION CHECK]

1. Which function type describes a function that takes two Int values and returns a Boolean?

2. What happens when a lambda with exactly one parameter does not name that parameter?

3. Why did shippingFunction have to be a var instead of a val in the task?