Kotlin Lambda 高阶函数
系统讲授 Kotlin 函数类型与带接收者函数类型、Lambda 语法与上下文推断、高阶函数与尾随 Lambda、集合 forEach/filter/map、可变闭包捕获、匿名函数、:: 引用与 SAM 转换。
学完这一章,你能够
- 系统讲授 Kotlin 函数类型与带接收者函数类型、Lambda 语法与上下文推断、高阶函数与尾随 Lambda、集合 forEach/filter/map、可变闭包捕获、匿名函数、:: 引用与 SAM 转换。
函数类型与带接收者函数类型
在 Kotlin 中函数是一等公民,可存入变量、作为参数传递或作为返回值返回。函数类型写作 `(参数类型) -> 返回类型`(如 `(Int, Int) -> Int`、`() -> Unit`),可空函数类型需在外层加括号 `((Int) -> Int)?` 并用 `callback?.invoke(21)` 安全调用;形参名如 `(x: Int, y: Int) -> Int` 仅作文档提示不影响类型兼容性。带接收者的函数类型写作 `String.(Int) -> String`,内部以 `this` 访问接收者,既可按扩展语法 `"Sky".repeatFun(2)` 调用,也可直接赋给等价普通函数类型 `(String, Int) -> String` 将接收者转为首个参数。
Lambda 语法、高阶函数与集合管道
Lambda 用花括号包裹,`->` 左侧为参数、右侧为函数体,最后一个表达式即返回值;仅有一个参数且类型可推断时可省略参数声明改用隐式 `it`,Kotlin 1.1 起支持用 `_` 忽略未使用的参数。注意 Lambda 参数推断依赖目标上下文,如 `val f = { x -> x + 1 }` 缺少类型标注与上下文目标时会编译报错。
接收函数参数或返回函数的高阶函数把通用流程与具体策略解耦。当最后一个参数是函数类型时可将 Lambda 移出圆括号形成尾随 Lambda(trailing lambda);若仅此一个参数甚至可省略空括号,如 `list.forEach { ... }`。
集合标准库大量运用高阶函数:`forEach` 遍历执行副作用并返回 `Unit`,`filter` 筛选元素、`map` 转换元素,两者均返回新列表而不修改原集合;因三者皆为内联函数,不会为 Lambda 额外分配函数对象。需索引时可用 `forEachIndexed { index, value -> ... }`,遍历 `Map` 则可直接解构 `(key, value)`。
可变闭包捕获与匿名函数
Lambda 能够捕获定义时所在词法作用域的变量构成闭包(closure)。与 Java 要求被捕获变量必须 effectively final 不同,Kotlin 允许闭包捕获并修改外层 `var` 变量;工厂函数 `makeCounter()` 每次调用都会生成持有独立 `count` 状态的闭包实例。
匿名函数以 `fun(a: Int, b: Int): Int { ... }` 声明,支持显式写出返回类型;其关键差异在于匿名函数内部的无标签 `return` 仅从匿名函数自身返回,不会跳出外层 `main` 函数,因此在 `forEach(fun(value) { if (value == 3) return; ... })` 中只跳过当前元素。
可调用引用 ::、构造器引用与 SAM 转换
已有具名声明时可直接用 `::` 获取函数值而无需再套一层 Lambda:包括顶层函数引用 `::isEven`、绑定到具体实例的引用 `site::hello`(及绑定属性引用 `site::name`)、未绑定成员引用 `Site::hello`(类型为 `(Site) -> String`)以及构造器引用 `::Site`(类型为 `(String, String) -> Site`);存在同名重载时由目标函数类型决定匹配项。
对于仅含单个抽象方法的接口(SAM),Kotlin 允许直接以 Lambda 创建其实例:对 Java 接口(如 `Runnable { ... }`)天然支持,对 Kotlin 接口则自 Kotlin 1.4 起通过 `fun interface` 声明开启 SAM 转换;未加 `fun` 的普通单方法 Kotlin 接口仍须使用对象表达式实现。
Lambda 与高阶函数常见问题速查
| 问题 | 说明 |
|---|---|
| Lambda 里的 return 从哪返回 | 传给内联函数时直接从外层函数非局部返回;使用 return@标签 则仅结束当前 Lambda。 |
| filter 和 map 会修改原集合吗 | 不会,两者均生成并返回新列表,原集合保持不变。 |
| it 什么时候能用 | 仅在单参数且上下文可推断类型时可用;多参数 Lambda 必须显式写出各参数名。 |
| 函数引用和 Lambda 怎么选 | 直接转发给已有命名函数或构造器时优先用 ::;需组合额外逻辑时写 Lambda。 |
| SAM 转换能用于任何接口吗 | 不能,接口必须仅有一个抽象方法,且 Kotlin 接口必须使用 fun interface 声明。 |
离线校验函数类型、接收者 Lambda、集合高阶管道、可变闭包、:: 引用与 SAM 转换
"""Offline Kotlin 2.x semantic verifier for Chapter 14 (lambda)."""
from dataclasses import dataclass
import json
import sys
from typing import Callable
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
@dataclass
class Site:
name: str
url: str = "www.mbsky.com"
def hello(self) -> str:
return f"你好,{self.name}"
def is_even(v: int) -> bool:
return v % 2 == 0
def calculate(a: int, b: int, op: Callable[[int, int], int]) -> int:
return op(a, b)
def multiplier(factor: int) -> Callable[[int], int]:
return lambda v: v * factor
def make_counter() -> Callable[[], int]:
count = 0
def inc() -> int:
nonlocal count
count += 1
return count
return inc
class StringChecker:
"""Models Kotlin `fun interface StringChecker { fun check(value: String): Boolean }`."""
def __init__(self, fn: Callable[[str], bool]) -> None:
self._fn = fn
def check(self, value: str) -> bool:
return self._fn(value)
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Function types, nullable function type ?.invoke, receiver function type
sum_fn: Callable[[int, int], int] = lambda a, b: a + b
greet_fn: Callable[[str], str] = lambda name: f"你好,{name}"
callback: Callable[[int], int] | None = None
null_call = callback(21) if callback is not None else None
callback = lambda it: it * 2
non_null_call = callback(21) if callback is not None else None
repeat_fun: Callable[[str, int], str] = lambda this, times: this * times
actual_1 = {
"sum_1_2": sum_fn(1, 2),
"greet": greet_fn("Mbsky"),
"nullable_before_assign": null_call,
"nullable_after_assign": non_null_call,
"receiver_as_ext": repeat_fun("Sky", 2),
"receiver_as_plain": repeat_fun("MBSKY", 2),
}
expected_1 = {
"sum_1_2": 3,
"greet": "你好,Mbsky",
"nullable_before_assign": None,
"nullable_after_assign": 42,
"receiver_as_ext": "SkySky",
"receiver_as_plain": "MBSKYMBSKY",
}
cases.append({
"name": "function_types_and_receiver_lambdas",
"summary": "Verify function types, nullable function ?.invoke, and String.(Int) -> String interconversion.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Lambda syntax, trailing lambda, higher-order functions, collection pipelines
double_it = lambda it: it * 2
second_unused = lambda _, value: value
sites = ["mbsky", "MBSKY", "java", "kotlin"]
upper_only = [s for s in sites if s == s.upper()]
lengths = [len(s) for s in sites]
chained = [s.upper() for s in sites if s.lower().startswith("m")]
indexed = [f"{i} -> {v}" for i, v in enumerate(["Mbsky", "www.mbsky.com"])]
map_entries = [f"{k} = {v}" for k, v in {"name": "Mbsky", "site": "www.mbsky.com"}.items()]
actual_2 = {
"double_5": double_it(5),
"unused_param_second": second_unused(1, 2),
"hof_add_mul": [calculate(6, 3, lambda a, b: a + b), calculate(6, 3, lambda a, b: a * b)],
"hof_returned_fn": [multiplier(3)(5), multiplier(10)(4)],
"filter_upper": upper_only,
"map_lengths": lengths,
"filter_map_chain": chained,
"original_immutable": sites,
"for_each_indexed": indexed,
"map_for_each": map_entries,
}
expected_2 = {
"double_5": 10,
"unused_param_second": 2,
"hof_add_mul": [9, 18],
"hof_returned_fn": [15, 40],
"filter_upper": ["MBSKY"],
"map_lengths": [5, 5, 4, 6],
"filter_map_chain": ["MBSKY", "MBSKY"],
"original_immutable": ["mbsky", "MBSKY", "java", "kotlin"],
"for_each_indexed": ["0 -> Mbsky", "1 -> www.mbsky.com"],
"map_for_each": ["name = Mbsky", "site = www.mbsky.com"],
}
cases.append({
"name": "lambdas_hofs_and_collection_ops",
"summary": "Verify Lambda syntax, it, _, trailing lambdas, HOFs, and immutable filter/map/forEachIndexed pipelines.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Closures capturing mutable var + anonymous function local return
counter = 0
def inc_local() -> None:
nonlocal counter
counter += 1
inc_local()
inc_local()
c1 = make_counter()
c2 = make_counter()
c1(); c1(); c2()
anon_out: list[int] = []
def anon_fn(v: int) -> None:
if v == 3:
return # returns from anonymous function only
anon_out.append(v)
for item in [1, 2, 3, 4]:
anon_fn(item)
actual_3 = {
"captured_var_counter": counter,
"independent_closures": [c1(), c2()],
"anon_local_return_kept": anon_out,
"enclosing_continued": True,
}
expected_3 = {
"captured_var_counter": 2,
"independent_closures": [3, 2],
"anon_local_return_kept": [1, 2, 4],
"enclosing_continued": True,
}
cases.append({
"name": "closures_and_anonymous_function_return",
"summary": "Verify mutable var capture across independent closures and local return semantics of anonymous functions.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Function references (::top, bound, unbound, constructor ::Site) & SAM conversion
site = Site("Mbsky", "www.mbsky.com")
bound_ref = site.hello
unbound_ref = Site.hello
ctor_ref = Site
pairs = [("Mbsky", "www.mbsky.com"), ("MBSKY", "kotlin.mbsky.com")]
created = [ctor_ref(n, u) for n, u in pairs]
checker = StringChecker(lambda s: len(s) > 0)
actual_4 = {
"top_ref_filter": [n for n in [1, 2, 3, 4] if is_even(n)],
"bound_ref": bound_ref(),
"unbound_ref": unbound_ref(site),
"ctor_ref_names": [s.name for s in created],
"sam_non_empty": [checker.check("Mbsky"), checker.check("")],
"kotlin_fun_interface_since": "1.4",
}
expected_4 = {
"top_ref_filter": [2, 4],
"bound_ref": "你好,Mbsky",
"unbound_ref": "你好,Mbsky",
"ctor_ref_names": ["Mbsky", "MBSKY"],
"sam_non_empty": [True, False],
"kotlin_fun_interface_since": "1.4",
}
cases.append({
"name": "callable_references_and_sam_conversion",
"summary": "Verify top-level/bound/unbound/constructor :: references and fun interface SAM conversion.",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
return cases
def main() -> None:
payload = {"version": VERSION, "cases": run_cases()}
sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
- 离线脚本确认函数类型与 ?.invoke、filter/map 不可变链、独立可变闭包与匿名函数局部 return、绑定/未绑定/构造器引用及 fun interface SAM 转换全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
当前源码 SHA256:4ac13b6afaf94ee8f5211c1e99841b127cac8e63d13aa269a25f9ad1929753f0
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
ZIP SHA256:c8111cb684d0f16154dd76872c185284372b2f7745bbecdb6a99b8260ba1ff40
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Kotlin 中,`site::hello` 与 `Site::hello` 两种成员函数引用在类型签名与调用方式上有何区别?
展开参考解答
`site::hello` 是绑定引用,已经固定接收者实例 `site`,类型为 `() -> String`,调用时无需再传对象;`Site::hello` 是未绑定引用,类型为 `(Site) -> String`,调用时必须把目标 `Site` 实例作为第一个参数传入。