Kotlin中的嵌套Lambda调用 [英] Nested lambda calls in Kotlin
本文介绍了Kotlin中的嵌套Lambda调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Kotlin中嵌套lambda调用时,如何明确引用孩子和父母的it
元素?例如:
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} }
推荐答案
it
始终引用最内部的lambda参数,要访问外部参数,则必须命名它们.例如:
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} }
(您可以将内部的内容保留为it
,但我认为也可以更好一点).
(You could leave the inner one as it
, but it's a bit nicer if you name that too, in my opinion.)
编辑:@ mfulton26链接了下面的相关文档,请参阅该文档以获取更多详细信息.
@mfulton26 linked the relevant documentation below, see that for more details.
这篇关于Kotlin中的嵌套Lambda调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文