Is there any requirement to ready for learning chapter 5 [: Anonymous functions]?

I quickly understood chapters before. but in chapter 5 I really confused with “Anonymous Functions”. why we should use. I read this chapter 4 times in a row. but some parts is really dark for me. for example in this part (Listing 5.8 Passing a lambda with the shorthand syntax (SimVillage.kt)):

fun main(args: Array<String>) {
    runSimulation("Guyal") { playerName, numBuildings ->
        val currentYear = 2018
        println("Adding $numBuildings houses")
        "Welcome to SimVillage, $playerName! (copyright $currentYear)"
   }
}

fun runSimulation(playerName: String, greetingFunction: (String, Int) -> String) {
   val numBuildings = (1..3).shuffled().last()   // Randomly selects 1, 2, or 3
   println(greetingFunction(playerName, numBuildings))
}

we run runSimulation with parameter. in last line of runSimulation body we’re going to print greetingFunction that is a parameter for runSimulation. I mean where is the body of greetingFunction ?!
I searched for other references for this chapter but I can’t understand this chapter. I know I’m beginner and it’s first time I start learning a language but is there any simple tutorial for this chapter? or I’m in wrong way and need some requirements from JAVA?
I can’t skip this chapter and I need to read lot about it.

I would strongly recommend learning anonymous functions and lambda expressions. Anonymous functions are a standard part of the language. Though anonymous functions are not used as frequently as regular, normal functions, it is likely you will come across one at some point. If you come across them in a code base, you’ll want to understand what is happening.

An anonymous function is simply a function without a name. Note that there is a difference between anonymous functions and lambda expressions.

The code bolded below is a lambda expression:
fun main(args: Array) {
    runSimulation(“Guyal”) { playerName, numBuildings →
        val currentYear = 2018
        println(“Adding $numBuildings houses”)
        “Welcome to SimVillage, $playerName! (copyright $currentYear)”
    }
}

In case it is hard to see where the bolding starts, the lambda function begins starting from the first opening curly brace after runSimulation("Guyal")

Lambda expressions are a very useful shorthand technique and can simplify your code. They are helpful if you plan to learn about more advanced topics such as streams and/or reactive programming. You can use Lambda expressions in Java but it is not required for you to know about them prior to learning about them in Kotlin. They are very similar in concept anyway.

runSimulation has 2 parameters, as you can see from the function definition:

fun runSimulation(playerName: String, greetingFunction: (String, Int) -> String) {
   val numBuildings = (1..3).shuffled().last()   // Randomly selects 1, 2, or 3
   println(greetingFunction(playerName, numBuildings))
}

The two parameters are playerName (a String) and greetingFunction (a function that takes in a String and Int, then returns a String). Going back to the main function, we can see that runSimulation is being invoked. It looks like it is only taking in 1 parameter, “Guyal”, but it is actually taking in 2 parameters. The 2nd parameter is a lambda expression and represents a function.

The explanation of why this code looks so weird:

In Kotlin, there is a convention: if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses:
val product = items.fold(1) { acc, e -> acc * e }
Such syntax is also known as trailing lambda.
source: https://kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter

So you are actually seeing 2 parameters being passed into the runSimulation invocation.

Let’s deconstruct the lambda expression now.

fun main(args: Array) {
    runSimulation(“Guyal”) { playerName, numBuildings
        val currentYear = 2018
        println(“Adding $numBuildings houses”)
        “Welcome to SimVillage, $playerName! (copyright $currentYear)”
    }
}

The bolded parts in the above code snippet represent the body of the function. The italicized parts represent the parameters to the function. The function as a whole is being passed into the runSimulation function as a 2nd parameter (this function is assigned the local variable name greetingFunction). The last line is a standalone string that is returned. greetingFunction returns a string, and that returned string is printed in the last line of runSimulation.

To better understand the basic idea behind lambda expressions and anonymous function, I recommend reading the kotlinlang.org segments on the two topics to supplement your reading.
Anonymous Functions: https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions
Lambda Expressions: https://kotlinlang.org/docs/reference/lambdas.html#lambda-expression-syntax

1 Like