在Kotlin中嵌套lambda调用时,如何明确地引用子元素和父元素it
元素?例如:
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} }
答案 0 :(得分:27)
it
总是引用最里面的lambda参数,要访问外部参数,你必须命名它们。例如:
list1.filter { a -> list2.none { b -> a.weekday == b.weekday && a.time == b.time} }
(你可以把内部的那个留给it
,但是如果你在我看来这个名字也更好一些。)
编辑: @ mfulton26链接了以下相关文档,有关详细信息,请参阅。