Nested lambda calls in Kotlin

烈酒焚心 提交于 2019-11-28 07:02:48

问题


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} }

回答1:


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.



来源:https://stackoverflow.com/questions/43042385/nested-lambda-calls-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!