Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested lambda calls in Kotlin

Tags:

kotlin

When nesting lambda calls in Kotlin, how can I unambiguously refer to child's and parent's it element? For instance:

data class Course(var weekday: Int, var time: Int, var duration: Int)
var list1 = mutableListOf<Course>()
var list2 = mutableListOf<Course>()
// populate list1 and list2
// exclude any element from list1 if it has the same time and weekday as any element from list2
list1.filter { list2.none{it.weekday == it.weekday && it.time == it.time} }
like image 502
arslancharyev31 Avatar asked Mar 27 '17 09:03

arslancharyev31


People also ask

How do you pass lambda as parameter Kotlin?

In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.

What is trailing lambda in Kotlin?

To help deal with this, Kotlin supports a specific kind of syntax referred to as trailing lambda syntax. This syntax states that if the final parameter to a function is another function, then the lambda can be passed outside of the function call parentheses.

Why do we use lambda in Kotlin?

Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.


1 Answers

it always refers to the innermost lambda's parameter, to access outer ones, you have to name them. For example:

list1.filter { a -> list2.none { b -> a.weekday == b.weekday && a.time == b.time} }

(You could leave the inner one as it, but it's a bit nicer if you name that too, in my opinion.)

Edit: @mfulton26 linked the relevant documentation below, see that for more details.

like image 131
zsmb13 Avatar answered Oct 26 '22 20:10

zsmb13