首页 文章

在Kotlin中嵌套的lambda调用

提问于
浏览
13

在Kotlin中嵌套lambda调用时,如何明确地引用子's and parent' s 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} }

1 回答

  • 24

    it 始终引用最里面的lambda参数,要访问外部参数,必须命名它们 . 例如:

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

    (你可以把内部的那个留作 it ,但是如果你这么说的话,它会更好一点,在我看来 . )

    Edit: @ mfulton26链接了下面的相关文档,有关详细信息,请参阅 .

相关问题