kotlin - Lambda 表达式的以下代码是如何执行的?
问题描述
我创建了一个 customFilter 来理解 Kotlin 中的 Lambda 表达式。代码如下;
我已经了解我们如何创建自己的自定义过滤器函数,如何在高阶函数中传递 lambda,但无法弄清楚这些行的执行顺序。
//Create a class extension function on List<Shape> called customFilter which takes a lambda function as argument
//and returns a Boolean value. The class extension function returns a List
fun List<Shape>.customFilter(filterFunction: (Shape, String) -> (Boolean)): List<Shape> {
val resultList = mutableListOf<Shape>()
for (shape in this) {
if (filterFunction(shape)) {
resultList.add(shape)
}
}
return resultList
}
fun main(){
//assume all the following instances has been created.
var shapes2 = listOf(circle1, circle2, triangle1, triangle2, rectangle1, rectangle2)
shapes2 = shapes2.customFilter { shape, stringVar ->
println(stringVar)
shape.area() > 20
}.sortedBy { item -> item.area() }
}
在下面的代码中,将根据哪个条件计算总和?
fun main() {
val list = (1..5).toList()
val sum = list.customSum { item -> item % 2 == 0 }
println(sum)
}
fun List<Int>.customSum(sumFunction: (Int) -> Boolean): Int {
var sum = 0
for (number in this) {
if (number % 2 == 1)
sum += number
}
return sum
}
解决方案
您的 lambda 被传递给您的 customFilter 函数,也就是它被执行的时候。
操作的顺序,如果你要从图片中去掉 lambda-passing,可能是这样的:
fun customFilteredList(shapes: List<Shape>): List<Shape> {
val resultList = mutableListOf<Shape>()
for (shape in shapes) {
if (shape.area() > 20) {
resultList.add(shape)
}
}
return resultList
}
fun main() {
// same instances from before
val shapesBefore = listOf(circle1, circle2, triangle1, triangle2, rectangle1, rectangle2)
val shapesAfter = customFilteredList(shapesBefore)
// do more stuff
}
我希望区别很明显。通过定义任何接受 lambda(而不仅仅是一个过滤器)的函数,您正在将对该整个 lambda(其本身的范围)的引用传递给您的函数。届时,您的函数将在其自己的范围内执行 lambda。main()
所有这些都在您的调用范围内执行。
顺便说一句,这可能也有帮助(它对我有用)是filter
在 kotlin 标准库中实现的 lambda 接受函数。
fun main() {
val shapes = listOf(circle1, circle2, triangle1, triangle2, rectangle1, rectangle2).filter { shape ->
shape.area() > 20
}
}
我不确定你stringVar
来自哪里,所以我不确定除了打印它之外,你期望它在你的功能中发生什么。如果没有更多上下文来说明为什么在更新列表时需要该字符串,这实际上是没有意义的。
推荐阅读
- sql - 将重复列设为 NULL
- visual-studio-code - 如何使用 API 在 vscode 市场中发布 vscode 插件?
- r - R:我如何多次使用带有矩阵的滞后命令?
- python - 使用 dict 作为函数的输入,但只接受函数需要的参数
- c# -
和 xmlns:local - authentication - 通过 CMD 使用密码作为参数的 Tectia SSH 登录
- google-sheets-api - 如何将日期转换为 Google 表格中的文本
- java - Java - 为什么字符串拆分为空字符串给我一个非空数组?
- r - R循环从多个数据框中选择特定列
- angular - 如何处理 Angular 中的响应?