Learn

To simplify how we define functions, we can use function literals. A function literal is an unnamed function that can be treated as a value: we can call them, assign them as variables, pass them as arguments, and return them from a function as we could with any other value.

We’ll be going over two types of function literals: anonymous functions and lambda expressions. While anonymous functions and lambda expressions serve the same purpose, they use a slightly different syntax.

To start, let’s create an anonymous function stored in a variable called `quotient` that returns the quotient of two numbers:

``````val quotient = fun(num1: Int, num2: Int): Double {
return num1 / num2
}``````
• The anonymous function is contained in a variable called `quotient`.
• The `fun` keyword is placed after the assignment operator and is not followed by a name (hence the anonymous).
• `quotient` has a function type of `(Double, Double) -> Double`.

The function type describes the argument type and return type of the anonymous function. The arguments are contained within parentheses while the return type is stated after `->`. In this case, the anonymous function takes in two Doubles and returns a single Double.

To call this anonymous function, we’ll simply call `quotient` like we would any other variable:

``println(quotient(10, 5)) // Prints: 2``

A lambda expression is very similar to an anonymous function; however, its concise syntax makes lambda expressions a more popular option amongst programmers. It’s suggested to use a lambda expression over an anonymous function when creating a function with only one expression.

If we were to recreate our `quotient` variable using a lambda expression, our code would look like this:

``````val quotient = { num1: Int, num2: Int -> num1 / num2 }

println(quotient(10, 5)) // Prints: 2``````
• The lambda expression is contained within brackets: `{` and `}`
• We state the parameter names as well as their data types.
• The return value `num1 / num2` is placed after the `->` symbol.
• Including the return type is optional because the compiler can use type inference to deduce the data type of the return value.

### Instructions

1.

Working at a landscape company, a customer asks for grass to cover the area of their triangle-shaped yard.

Create a variable called `area` and sets its value to an anonymous function that accepts two Int arguments: `base` and `height` and returns an Int value.

The return value should equal `(base * height) / 2`.

Use `println()` to output the value of `area(15, 19)`.

2.

The customer comes back and asks for you to build a fence around their garden.

Create a variable called `perimeter` and sets its value to a lambda expression that accepts two Int values called `side1` and `side2` and returns an Int value.

The return value will equal the value of `side1 + side2` times 2.

Use `println()` to output the value of `perimeter(15, 24)`.