Kotlin 中使用函数式编程详解
函数式编程(Functional Programming)是一种编程范式,它将计算视为数学函数的求值,并避免状态变化和可变数据。Kotlin 完美支持函数式编程,同时保持了面向对象编程的优势。
一、函数式编程核心概念
1. 一等公民函数
函数可以作为参数传递、作为返回值、存储在变量中。
// 将函数存储在变量中
val add: (Int, Int) -> Int = { a, b -> a + b }
val multiply = { a: Int, b: Int -> a * b }
// 函数作为参数
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
// 函数作为返回值
fun getOperation(type: String): (Int, Int) -> Int {
return when (type) {
"add" -> { x, y -> x + y }
"multiply" -> { x, y -> x * y }
else -> { x, y -> x - y }
}
}
fun main() {
println(calculate(5, 3, add)) // 8
println(calculate(5, 3, multiply)) // 15
val operation = getOperation("add")
println(operation(10, 20)) // 30
}
2. 纯函数
相同输入总是产生相同输出,没有副作用。
// 纯函数:没有副作用,只依赖于输入
fun pureAdd(a: Int, b: Int): Int = a + b
// 非纯函数:有副作用
var counter = 0
fun impureAdd(a: Int, b: Int): Int {
counter++ // 副作用:修改了外部状态
println("计算次数: $counter") // 副作用:I/O操作
return a + b
}
// 纯函数示例:列表处理
fun pureProcess(numbers: List<Int>): List<Int> {
return numbers
.filter { it > 0 }
.map { it * 2 }
.sorted()
}
fun main() {
println(pureAdd(2, 3)) // 总是 5
println(impureAdd(2, 3)) // 有副作用
}
3. 不可变性
尽可能使用不可变数据。
// 不可变变量
val immutableList = listOf(1, 2, 3, 4, 5)
// 函数式操作返回新集合,不修改原集合
val doubled = immutableList.map { it * 2 }
val filtered = immutableList.filter { it > 2 }
// 使用不可变数据类
data class User(val name: String, val age: Int)
// 创建新对象而不是修改
val user1 = User("Alice", 25)
val user2 = user1.copy(age = 26) // 创建新对象,不修改 user1
println(user1) // User(name=Alice, age=25)
println(user2) // User(name=Alice, age=26)
二、高阶函数实践
1. 常用高阶函数模式
// 函数组合
fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C = { x -> f(g(x)) }
// 柯里化(Currying):将多参数函数转换为单参数函数链
fun add(x: Int, y: Int): Int = x + y
// 柯里化版本
fun curriedAdd(x: Int): (Int) -> Int = { y -> x + y }
// 部分应用
fun add5(): (Int) -> Int = { y -> 5 + y }
// 函数管道
fun <T> T.pipe(vararg functions: (T) -> T): T {
return functions.fold(this) { acc, func -> func(acc) }
}
fun main() {
// 函数组合
val addOne = { x: Int -> x + 1 }
val multiplyByTwo = { x: Int -> x * 2 }
val composed = compose(multiplyByTwo, addOne)
println(composed(5)) // (5+1)*2 = 12
// 柯里化
val addFive = curriedAdd(5)
println(addFive(3)) // 8
// 管道操作
val result = 5.pipe(
{ it + 1 },
{ it * 2 },
{ it - 3 }
)
println(result) // ((5+1)*2)-3 = 9
}
2. 自定义高阶函数
// 自定义 map 函数
fun <T, R> Iterable<T>.myMap(transform: (T) -> R): List<R> {
val result = mutableListOf<R>()
for (item in this) {
result.add(transform(item))
}
return result
}
// 自定义 filter 函数
fun <T> Iterable<T>.myFilter(predicate: (T) -> Boolean): List<T> {
val result = mutableListOf<T>()
for (item in this) {
if (predicate(item)) {
result.add(item)
}
}
return result
}
// 自定义 reduce 函数
fun <T, R> Iterable<T>.myReduce(
initial: R,
operation: (acc: R, T) -> R
): R {
var accumulator = initial
for (element in this) {
accumulator = operation(accumulator, element)
}
return accumulator
}
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val squares = numbers.myMap { it * it }
println(squares) // [1, 4, 9, 16, 25]
val evens = numbers.myFilter { it % 2 == 0 }
println(evens) // [2, 4]
val sum = numbers.myReduce(0) { acc, num -> acc + num }
println(sum) // 15
}
三、集合的函数式操作
1. 转换操作
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 35),
Person("David", 40)
)
// map: 转换每个元素
val names = people.map { it.name }
println("Names: $names") // [Alice, Bob, Charlie, David]
// flatMap: 扁平化映射
val chars = people.flatMap { it.name.toList() }
println("Characters: $chars") // [A, l, i, c, e, B, o, b, ...]
// flatten: 扁平化嵌套集合
val nested = listOf(listOf(1, 2), listOf(3, 4), listOf(5, 6))
val flat = nested.flatten()
println("Flattened: $flat") // [1, 2, 3, 4, 5, 6]
// associate: 创建映射
val ageMap = people.associate { it.name to it.age }
println("Age Map: $ageMap") // {Alice=25, Bob=30, Charlie=35, David=40}
// groupBy: 分组
val byAgeRange = people.groupBy {
when (it.age) {
in 20..29 -> "20s"
in 30..39 -> "30s"
else -> "40+"
}
}
println("Grouped: $byAgeRange")
}
2. 过滤操作
fun main() {
val numbers = (1..20).toList()
// 基本过滤
val evens = numbers.filter { it % 2 == 0 }
// 去除空值
val withNulls = listOf(1, null, 2, null, 3)
val nonNulls = withNulls.filterNotNull()
// 类型过滤
val mixed = listOf("text", 123, 45.6, "another")
val strings = mixed.filterIsInstance<String>()
// 分区:同时获取满足和不满足条件的元素
val (positive, negative) = numbers.partition { it > 10 }
println(">10: $positive, <=10: $negative")
// 去重
val duplicates = listOf(1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
val unique = duplicates.distinct()
println("Unique: $unique") // [1, 2, 3, 4]
// 根据属性去重
data class Student(val id: Int, val name: String)
val students = listOf(
Student(1, "Alice"),
Student(2, "Bob"),
Student(1, "Alice"), // 重复
Student(3, "Charlie")
)
val uniqueStudents = students.distinctBy { it.id }
println("Unique students: $uniqueStudents")
}
3. 聚合操作
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// reduce: 从第一个元素开始累积
val sum = numbers.reduce { acc, num -> acc + num }
println("Sum: $sum") // 15
// fold: 提供初始值
val product = numbers.fold(1) { acc, num -> acc * num }
println("Product: $product") // 120
// runningReduce / runningFold: 获取中间结果
val runningSum = numbers.runningReduce { acc, num -> acc + num }
println("Running sum: $runningSum") // [1, 3, 6, 10, 15]
// 统计操作
println("Count: ${numbers.count()}")
println("Sum: ${numbers.sum()}")
println("Average: ${numbers.average()}")
println("Min: ${numbers.minOrNull()}")
println("Max: ${numbers.maxOrNull()}")
// 自定义聚合
val stats = numbers.fold(Stats()) { stats, num ->
stats.apply {
count++
sum += num
min = if (num < min) num else min
max = if (num > max) num else max
}
}
println("Custom stats: $stats")
}
data class Stats(
var count: Int = 0,
var sum: Int = 0,
var min: Int = Int.MAX_VALUE,
var max: Int = Int.MIN_VALUE
) {
val average: Double get() = if (count > 0) sum.toDouble() / count else 0.0
}
4. 查找操作
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// 查找第一个匹配的元素
val firstEven = numbers.find { it % 2 == 0 }
val lastOdd = numbers.findLast { it % 2 != 0 }
// 查找满足条件的索引
val index = numbers.indexOfFirst { it > 5 }
val lastIndex = numbers.indexOfLast { it < 8 }
// 检查是否存在
val hasEven = numbers.any { it % 2 == 0 }
val allPositive = numbers.all { it > 0 }
val noneNegative = numbers.none { it < 0 }
// 取元素
val firstThree = numbers.take(3)
val lastThree = numbers.takeLast(3)
val whileLessThan5 = numbers.takeWhile { it < 5 }
val dropFirst3 = numbers.drop(3)
val dropWhileLessThan5 = numbers.dropWhile { it < 5 }
println("First 3: $firstThree") // [1, 2, 3]
println("While <5: $whileLessThan5") // [1, 2, 3, 4]
println("Drop first 3: $dropFirst3") // [4, 5, 6, 7, 8, 9, 10]
println("Drop while <5: $dropWhileLessThan5") // [5, 6, 7, 8, 9, 10]
}
四、序列与惰性求值
1. 序列基础
fun main() {
// List:立即求值
val listResult = (1..1_000_000)
.filter { it % 2 == 0 }
.map { it * 2 }
.take(10)
.toList()
// Sequence:惰性求值
val sequenceResult = (1..1_000_000)
.asSequence()
.filter {
println("过滤: $it")
it % 2 == 0
}
.map {
println("映射: $it")
it * 2
}
.take(10)
.toList()
println("List 结果: $listResult")
println("Sequence 结果: $sequenceResult")
// 生成无限序列
val naturalNumbers = generateSequence(1) { it + 1 }
val first10 = naturalNumbers.take(10).toList()
println("前10个自然数: $first10") // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 基于种子的序列
val fibonacci = sequence {
var a = 0
var b = 1
yield(a)
yield(b)
while (true) {
val next = a + b
yield(next)
a = b
b = next
}
}
val first10Fibonacci = fibonacci.take(10).toList()
println("前10个斐波那契数: $first10Fibonacci") // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
}
2. 序列性能优化
data class Product(val id: Int, val name: String, val price: Double, val category: String)
fun getProducts() = listOf(
Product(1, "Laptop", 999.99, "Electronics"),
Product(2, "Mouse", 29.99, "Electronics"),
Product(3, "Desk", 199.99, "Furniture"),
Product(4, "Chair", 149.99, "Furniture"),
Product(5, "Book", 19.99, "Books"),
Product(6, "Monitor", 299.99, "Electronics"),
Product(7, "Keyboard", 79.99, "Electronics"),
Product(8, "Lamp", 49.99, "Home"),
Product(9, "Tablet", 399.99, "Electronics"),
Product(10, "Printer", 149.99, "Electronics")
)
fun main() {
val products = getProducts()
// 普通集合操作:创建多个中间集合
val expensiveElectronics = products
.filter { it.category == "Electronics" } // 中间集合1
.filter { it.price > 100 } // 中间集合2
.sortedByDescending { it.price } // 中间集合3
.take(3) // 中间集合4
.map { it.name } // 中间集合5
println("普通操作结果: $expensiveElectronics")
// 序列操作:惰性求值,减少中间集合
val expensiveElectronicsSequence = products.asSequence()
.filter {
println("过滤类别: ${it.name}")
it.category == "Electronics"
}
.filter {
println("过滤价格: ${it.name}")
it.price > 100
}
.sortedByDescending { it.price }
.take(3)
.map { it.name }
.toList()
println("序列操作结果: $expensiveElectronicsSequence")
}
五、函数式设计模式
1. Either 类型(错误处理)
// 函数式错误处理
sealed class Either<out L, out R> {
data class Left<out L>(val value: L) : Either<L, Nothing>()
data class Right<out R>(val value: R) : Either<Nothing, R>()
// 转换函数
fun <T> fold(leftOp: (L) -> T, rightOp: (R) -> T): T = when (this) {
is Left -> leftOp(value)
is Right -> rightOp(value)
}
fun isLeft() = this is Left<L>
fun isRight() = this is Right<R>
// 链式操作
fun <T> map(transform: (R) -> T): Either<L, T> = when (this) {
is Left -> Left(value)
is Right -> Right(transform(value))
}
fun <T> flatMap(transform: (R) -> Either<L, T>): Either<L, T> = when (this) {
is Left -> Left(value)
is Right -> transform(value)
}
}
// 使用示例
fun divide(a: Int, b: Int): Either<String, Int> {
return if (b == 0) {
Either.Left("除数不能为零")
} else {
Either.Right(a / b)
}
}
fun parseNumber(str: String): Either<String, Int> {
return try {
Either.Right(str.toInt())
} catch (e: NumberFormatException) {
Either.Left("无效的数字: $str")
}
}
fun main() {
// 链式调用
val result = parseNumber("10")
.flatMap { a -> parseNumber("2") }
.flatMap { b -> divide(a, b) }
when (result) {
is Either.Left -> println("错误: ${result.value}")
is Either.Right -> println("结果: ${result.value}")
}
// 使用 fold
val message = result.fold(
leftOp = { error -> "失败: $error" },
rightOp = { value -> "成功: $value" }
)
println(message)
}
2. Option/Maybe 类型(空值处理)
sealed class Option<out T> {
data class Some<out T>(val value: T) : Option<T>()
object None : Option<Nothing>()
companion object {
fun <T> of(value: T?): Option<T> = if (value != null) Some(value) else None
}
// 转换和组合
fun <R> map(transform: (T) -> R): Option<R> = when (this) {
is Some -> Some(transform(value))
None -> None
}
fun <R> flatMap(transform: (T) -> Option<R>): Option<R> = when (this) {
is Some -> transform(value)
None -> None
}
fun getOrElse(default: T): T = when (this) {
is Some -> value
None -> default
}
fun orElse(alternative: () -> Option<T>): Option<T> = when (this) {
is Some -> this
None -> alternative()
}
}
// 使用示例
data class User(val id: Int, val name: String, val managerId: Option<Int>)
fun findUser(id: Int): Option<User> {
val users = mapOf(
1 to User(1, "Alice", Option.None),
2 to User(2, "Bob", Option.Some(1)),
3 to User(3, "Charlie", Option.Some(2))
)
return Option.of(users[id])
}
fun main() {
val user = findUser(2)
// 链式操作
val managerName = user
.flatMap { it.managerId }
.flatMap { findUser(it) }
.map { it.name }
.getOrElse("无经理")
println("经理姓名: $managerName") // Alice
// 组合多个 Option
val user1 = findUser(1)
val user2 = findUser(2)
val combined = user1.flatMap { u1 ->
user2.map { u2 ->
"${u1.name} 和 ${u2.name}"
}
}
println("组合: ${combined.getOrElse("无法组合")}")
}
3. State Monad(状态管理)
// 状态容器
data class State<S, out A>(val run: (S) -> Pair<A, S>) {
// 组合状态操作
fun <B> map(transform: (A) -> B): State<S, B> = State { s ->
val (a, s2) = this.run(s)
transform(a) to s2
}
fun <B> flatMap(transform: (A) -> State<S, B>): State<S, B> = State { s ->
val (a, s2) = this.run(s)
transform(a).run(s2)
}
}
// State 工具函数
fun <S, A> unit(a: A): State<S, A> = State { s -> a to s }
fun <S> getState(): State<S, S> = State { s -> s to s }
fun <S> setState(s: S): State<S, Unit> = State { _ -> Unit to s }
fun <S> modify(transform: (S) -> S): State<S, Unit> = State { s ->
Unit to transform(s)
}
// 示例:计数器
data class CounterState(val count: Int, val max: Int)
fun increment(): State<CounterState, Int> = State { state ->
val newCount = state.count + 1
val newState = state.copy(count = newCount)
newCount to newState
}
fun decrement(): State<CounterState, Int> = State { state ->
val newCount = state.count - 1
val newState = state.copy(count = newCount)
newCount to newState
}
fun reset(): State<CounterState, Unit> = State { state ->
Unit to state.copy(count = 0)
}
fun main() {
val initialState = CounterState(0, 10)
// 组合状态操作
val program = unit<CounterState, Unit>(Unit)
.flatMap { increment() }
.flatMap { increment() }
.flatMap { decrement() }
.flatMap { reset() }
.flatMap { increment() }
val (result, finalState) = program.run(initialState)
println("结果: $result")
println("最终状态: $finalState") // CounterState(count=1, max=10)
}
六、函数式响应式编程(FRP)
1. 简单的事件流实现
// 简单的事件流
class EventStream<T>(initial: T) {
private val listeners = mutableListOf<(T) -> Unit>()
private var currentValue: T = initial
fun subscribe(listener: (T) -> Unit) {
listeners.add(listener)
listener(currentValue) // 立即通知当前值
}
fun emit(newValue: T) {
currentValue = newValue
listeners.forEach { it(newValue) }
}
// 函数式操作
fun <R> map(transform: (T) -> R): EventStream<R> {
val newStream = EventStream(transform(currentValue))
subscribe { newValue ->
newStream.emit(transform(newValue))
}
return newStream
}
fun filter(predicate: (T) -> Boolean): EventStream<T> {
val newStream = EventStream(currentValue)
subscribe { newValue ->
if (predicate(newValue)) {
newStream.emit(newValue)
}
}
return newStream
}
fun <R> scan(initial: R, operation: (R, T) -> R): EventStream<R> {
var accumulator = initial
val newStream = EventStream(accumulator)
subscribe { newValue ->
accumulator = operation(accumulator, newValue)
newStream.emit(accumulator)
}
return newStream
}
}
// 使用示例
fun main() {
val textStream = EventStream("")
// 创建派生流
val lengthStream = textStream.map { it.length }
val evenLengthStream = textStream.filter { it.length % 2 == 0 }
val lengthSumStream = textStream.scan(0) { acc, text -> acc + text.length }
// 订阅
textStream.subscribe { println("文本: $it") }
lengthStream.subscribe { println("长度: $it") }
evenLengthStream.subscribe { println("偶数长度文本: $it") }
lengthSumStream.subscribe { println("长度累计: $it") }
// 触发事件
textStream.emit("Hello")
textStream.emit("World")
textStream.emit("Kotlin")
}
七、性能优化与最佳实践
1. 避免中间集合
fun processLargeDataset() {
val largeList = (1..1_000_000).toList()
// 不好:创建多个中间集合
val bad = largeList
.filter { it % 2 == 0 } // 中间集合1(500,000 元素)
.map { it * 2 } // 中间集合2(500,000 元素)
.filter { it > 1000 } // 中间集合3(? 元素)
.take(100) // 中间集合4(100 元素)
// 好:使用序列
val good = largeList.asSequence()
.filter { it % 2 == 0 }
.map { it * 2 }
.filter { it > 1000 }
.take(100)
.toList()
// 更好:合并操作
val better = largeList.asSequence()
.filter {
val isEven = it % 2 == 0
val doubled = it * 2
isEven && doubled > 1000
}
.map { it * 2 }
.take(100)
.toList()
}
2. 记忆化(Memoization)
// 缓存函数结果
fun <T, R> memoize(function: (T) -> R): (T) -> R {
val cache = mutableMapOf<T, R>()
return { input: T ->
cache.getOrPut(input) { function(input) }
}
}
// 使用示例
val expensiveCalculation: (Int) -> Int = { x ->
println("计算 $x...")
Thread.sleep(1000) // 模拟耗时计算
x * x
}
fun main() {
val memoizedCalculation = memoize(expensiveCalculation)
println(memoizedCalculation(5)) // 计算 5...
println(memoizedCalculation(5)) // 从缓存获取,立即返回
println(memoizedCalculation(5)) // 从缓存获取,立即返回
println(memoizedCalculation(10)) // 计算 10...
}
3. 尾递归优化
// 普通递归(可能栈溢出)
fun factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
// 尾递归优化
tailrec fun factorialTailrec(n: Int, accumulator: Int = 1): Int {
return if (n <= 1) accumulator else factorialTailrec(n - 1, n * accumulator)
}
// 复杂尾递归示例
tailrec fun <T, R> List<T>.foldTailrec(
initial: R,
operation: (R, T) -> R,
index: Int = 0,
accumulator: R = initial
): R {
return if (index >= size) {
accumulator
} else {
val nextAcc = operation(accumulator, this[index])
foldTailrec(initial, operation, index + 1, nextAcc)
}
}
fun main() {
val largeList = (1..10000).toList()
// 使用尾递归
val sum = largeList.foldTailrec(0) { acc, num -> acc + num }
println("Sum: $sum") // 50005000
}
八、实际应用案例
1. 函数式数据验证
// 验证规则类型
typealias ValidationRule<T> = (T) -> ValidationResult
sealed class ValidationResult {
object Valid : ValidationResult()
data class Invalid(val message: String) : ValidationResult()
fun isValid(): Boolean = this is Valid
// 组合验证结果
infix fun and(other: ValidationResult): ValidationResult = when {
this is Invalid && other is Invalid ->
Invalid("${this.message}, ${other.message}")
this is Invalid -> this
other is Invalid -> other
else -> Valid
}
}
// 验证器
class Validator<T>(private val rules: List<ValidationRule<T>>) {
fun validate(value: T): ValidationResult {
return rules.fold(ValidationResult.Valid as ValidationResult) { acc, rule ->
acc and rule(value)
}
}
fun addRule(rule: ValidationRule<T>): Validator<T> {
return Validator(rules + rule)
}
}
// 验证规则构建器
fun <T> validator(block: Validator<T>.() -> Unit): Validator<T> {
return Validator<T>(emptyList()).apply(block)
}
// 使用示例
data class UserForm(
val username: String,
val email: String,
val age: Int,
val password: String
)
fun main() {
val userValidator = validator<UserForm> {
addRule { form ->
if (form.username.length >= 3) ValidationResult.Valid
else ValidationResult.Invalid("用户名至少3个字符")
}
addRule { form ->
if (form.email.contains("@")) ValidationResult.Valid
else ValidationResult.Invalid("邮箱格式不正确")
}
addRule { form ->
if (form.age in 18..120) ValidationResult.Valid
else ValidationResult.Invalid("年龄必须在18-120之间")
}
addRule { form ->
if (form.password.length >= 8) ValidationResult.Valid
else ValidationResult.Invalid("密码至少8个字符")
}
}
val testUser = UserForm("jo", "invalid-email", 15, "123")
val result = userValidator.validate(testUser)
when (result) {
is ValidationResult.Valid -> println("验证通过")
is ValidationResult.Invalid -> println("验证失败: ${result.message}")
}
}
2. 函数式配置构建器
// 配置 DSL
class ConfigBuilder {
private val config = mutableMapOf<String, Any>()
infix fun String.to(value: Any) {
config[this] = value
}
infix fun String.by(provider: () -> Any) {
config[this] = provider()
}
fun <T> with(key: String, block: (Any?) -> T): T {
return block(config[key])
}
fun build(): Map<String, Any> = config.toMap()
}
// 类型安全的配置
class DatabaseConfig private constructor(
val host: String,
val port: Int,
val username: String,
val password: String
) {
class Builder {
private var host: String = "localhost"
private var port: Int = 3306
private var username: String = "root"
private var password: String = ""
fun host(host: String) = apply { this.host = host }
fun port(port: Int) = apply { this.port = port }
fun username(username: String) = apply { this.username = username }
fun password(password: String) = apply { this.password = password }
fun build(): DatabaseConfig {
return DatabaseConfig(host, port, username, password)
}
}
}
// 使用示例
fun main() {
// DSL 风格
val config = ConfigBuilder().apply {
"database.host" to "localhost"
"database.port" to 5432
"app.name" by { "MyApp" }
"app.version" by { "1.0.0" }
}.build()
println("配置: $config")
// Builder 模式
val dbConfig = DatabaseConfig.Builder()
.host("192.168.1.100")
.port(3306)
.username("admin")
.password("secret")
.build()
println("数据库配置: $dbConfig")
}
九、函数式编程的最佳实践
1. 纯函数优先
// 不纯函数:有副作用
class ImpureCalculator {
private var lastResult: Int = 0
fun addAndStore(a: Int, b: Int): Int {
lastResult = a + b // 副作用
return lastResult
}
}
// 纯函数:无副作用
object PureCalculator {
fun add(a: Int, b: Int): Int = a + b
// 返回新状态而不是修改现有状态
fun addWithHistory(a: Int, b: Int, history: List<String>): Pair<Int, List<String>> {
val result = a + b
val newHistory = history + "$a + $b = $result"
return result to newHistory
}
}
fun main() {
// 使用纯函数
val (result1, history1) = PureCalculator.addWithHistory(2, 3, emptyList())
val (result2, history2) = PureCalculator.addWithHistory(4, 5, history1)
println("结果: $result2")
println("历史: $history2")
}
2. 组合优于继承
// 传统 OOP:继承
abstract class Animal {
abstract fun makeSound(): String
}
class Dog : Animal() {
override fun makeSound() = "Woof!"
}
class Cat : Animal() {
override fun makeSound() = "Meow!"
}
// 函数式:组合
typealias SoundMaker = () -> String
val dogSound: SoundMaker = { "Woof!" }
val catSound: SoundMaker = { "Meow!" }
// 组合声音
fun combineSounds(sound1: SoundMaker, sound2: SoundMaker): SoundMaker = {
"${sound1()} ${sound2()}"
}
// 修改声音
fun amplifySound(sound: SoundMaker, times: Int): SoundMaker = {
sound().repeat(times)
}
fun main() {
val dogCatSound = combineSounds(dogSound, catSound)
println(dogCatSound()) // Woof! Meow!
val loudDogSound = amplifySound(dogSound, 3)
println(loudDogSound()) // Woof!Woof!Woof!
}
3. 使用不可变数据
// 可变状态:容易出错
class MutableCounter {
var count = 0
fun increment() {
count++
}
}
// 不可变状态:安全
data class ImmutableCounter(val count: Int) {
fun increment(): ImmutableCounter = copy(count = count + 1)
}
// 状态转换:返回新状态
fun processCounter(counter: ImmutableCounter): Pair<ImmutableCounter, String> {
val newCounter = counter.increment()
val message = "计数增加到 ${newCounter.count}"
return newCounter to message
}
fun main() {
// 不可变状态处理
var counter = ImmutableCounter(0)
repeat(5) {
val (newCounter, message) = processCounter(counter)
println(message)
counter = newCounter
}
println("最终计数: ${counter.count}")
}
总结
Kotlin 的函数式编程能力非常强大,通过合理运用以下特性可以写出更简洁、安全、可维护的代码:
- 高阶函数和 Lambda:作为一等公民的函数
- 纯函数:减少副作用,提高可测试性
- 不可变数据:避免状态共享问题
- 集合操作:丰富的函数式集合 API
- 序列:惰性求值优化性能
- 函数组合:构建复杂逻辑
- 函数式数据类型:Option、Either、State 等
关键建议:
- 小步重构,逐步引入函数式风格
- 在性能关键路径使用序列
- 优先使用标准库函数式操作
- 注意空安全和异常处理
- 保持代码可读性和可维护性