Lambda

We already discussed how, if a function's last parameter is a lambda, it can't be passed outside the parenthesis and inside curly braces, as if the lambda itself is the body of a control structure.

We covered this unless function in Chapter 2, Getting Started with Functional Programming, in the section, First-class and high-order functions. Let's have a look at the following code:

fun unless(condition: Boolean, block: () -> Unit) {
if (!condition) block()
}

unless(someBoolean) {
println("You can't access this website")
}

Now, what happens if we combine vararg and lambda? Let's check it in the following code snippet:

fun <T, R> transform(vararg ts: T, f: (T) -> R): List<R> = ts.map(f)

Lambdas can be at the end of a function with a vararg parameter:

transform(1, 2, 3, 4) { i -> i.toString() }

Let's get a little adventurous, a vararg parameter of lambdas:

fun <T> emit(t: T, vararg listeners: (T) -> Unit) = listeners.forEach { listener ->
listener(t)
}

emit(1){i -> println(i)} //Compilation error. Passing value as a vararg is only allowed inside a parenthesized argument list

We can't pass a lambda outside of the parenthesis, but we can pass many lambdas inside:

emit(1, ::println, {i -> println(i * 2)})
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.139.169