Kotlin 函数类型

(type) -> type 是 Kotlin 中的一种‌函数类型 ‌,表示一个接收一个 type 类型参数并返回 type 类型结果的函数。它广泛用于高阶函数、Lambda 表达式和函数式编程场景

一、函数类型基础

1. ‌语法结构
  • 参数列表 ‌:括号内声明参数类型(如 (Int))。
  • 返回值类型 ‌:箭头 -> 后指定返回类型(如 Int)。
  • 完整形式 ‌:(参数类型1, 参数类型2, ...) -> 返回类型
2. ‌示例定义
kotlin 复制代码
// 声明一个函数类型变量
val square: (Int) -> Int = { num -> num * num }

println(square(5)) // 输出 25

二、函数类型的应用场景

1. ‌作为变量类型

将 Lambda 或匿名函数赋值给函数类型变量:

kotlin 复制代码
// Lambda 赋值
val increment: (Int) -> Int = { it + 1 }

// 匿名函数赋值
val decrement: (Int) -> Int = fun(x: Int): Int { return x - 1 }

println(increment(3)) // 输出 4
println(decrement(3)) // 输出 2
2. ‌作为函数参数(高阶函数)

接收函数类型参数以实现灵活逻辑:

kotlin 复制代码
// 高阶函数:对数字进行某种操作
fun processNumber(num: Int, operation: (Int) -> Int): Int {
    return operation(num)
}

// 使用 Lambda 传递操作
val result1 = processNumber(5, { it * 2 })   // 输出 10

// 使用函数引用传递操作
fun double(x: Int) = x * 2
val result2 = processNumber(5, ::double)    // 输出 10
3. ‌作为返回值

函数可以返回另一个函数:

kotlin 复制代码
fun getMultiplier(factor: Int): (Int) -> Int {
    return { num -> num * factor }
}

val triple = getMultiplier(3)
println(triple(4)) // 输出 12

三、与 Lambda 和匿名函数的关系

1. ‌Lambda 表达式

Lambda 是 (Int) -> Int 类型的实例,自动推断参数和返回类型:

kotlin 复制代码
val abs: (Int) -> Int = { x -> if (x >= 0) x else -x }
println(abs(-7)) // 输出 7
2. ‌匿名函数

需显式声明参数和返回类型,适合复杂逻辑:

kotlin 复制代码
val isEven = fun(num: Int): Int {
    return if (num % 2 == 0) 1 else 0
}
println(isEven(4)) // 输出 1

四、类型匹配与错误示例

1. ‌类型一致性

函数类型必须严格匹配参数和返回类型:

kotlin 复制代码
// 错误:返回类型不匹配(应为 Int,实际为 String)
val errorFunc: (Int) -> Int = { "Result: $it" } 

// 正确:返回类型匹配
val correctFunc: (Int) -> Int = { it.toString().length } 
2. ‌参数数量约束

参数数量必须与声明一致:

css 复制代码
// 错误:参数数量不匹配(应为 1 个参数)
val invalidFunc: (Int) -> Int = { a, b -> a + b } 

五、高阶函数实战示例

1. ‌自定义集合操作

实现类似 map 的功能:

kotlin 复制代码
fun List<Int>.customMap(transform: (Int) -> Int): List<Int> {
    val result = mutableListOf<Int>()
    for (item in this) {
        result.add(transform(item))
    }
    return result
}

val numbers = listOf(1, 2, 3)
val squared = numbers.customMap { it * it } // [1, 4, 9]
2. ‌策略模式

动态切换算法逻辑:

kotlin 复制代码
class Calculator {
    fun calculate(a: Int, b: Int, strategy: (Int, Int) -> Int): Int {
        return strategy(a, b)
    }
}

val addStrategy: (Int, Int) -> Int = { x, y -> x + y }
val multiplyStrategy: (Int, Int) -> Int = { x, y -> x * y }

val calc = Calculator()
println(calc.calculate(3, 4, addStrategy))      // 7
println(calc.calculate(3, 4, multiplyStrategy)) // 12

六、可空性与安全调用

1. ‌可空函数类型变量

声明可为空的函数类型并使用安全调用:

go 复制代码
var func: ((Int) -> Int)? = null

// 安全调用
func?.invoke(5) // 不会执行,因为 func 为 null

// 赋值后调用
func = { it + 10 }
println(func?.invoke(5)) // 输出 15
2. ‌结合 Elvis 运算符

提供默认函数实现:

kotlin 复制代码
val safeFunc: (Int) -> Int = func ?: { 0 }
println(safeFunc(5)) // 如果 func 为 null,输出 0

七、与 Java 的对比

1. ‌Java 的单一抽象方法(SAM)接口

Java 需通过接口(如 Function)实现类似功能:

ini 复制代码
// Java 示例
Function<Integer, Integer> square = x -> x * x;
System.out.println(square.apply(5)); // 输出 25
2. ‌Kotlin 的优势
  • 语法简洁 ‌:直接声明 (Int) -> Int,无需定义接口。
  • 原生支持‌:函数类型是 Kotlin 的一等公民,支持类型推断和灵活操作。

总结

(Int) -> Int 的核心要点:

  1. 定义 ‌:表示接收一个 Int 参数并返回 Int 的函数。

  2. 应用‌:

    • 作为变量、参数或返回值类型。
    • 结合 Lambda 或匿名函数实现动态逻辑。
  3. 优势‌:

    • 提升代码灵活性和可复用性。
    • 简化高阶函数的设计和使用。

使用建议‌:

  • 优先用 Lambda 实现简单逻辑。
  • 在需要显式类型或复杂逻辑时使用匿名函数。
  • 通过高阶函数抽象通用操作(如映射、过滤)。
相关推荐
Haha_bj18 小时前
七、Kotlin——扩展(Extensions)
android·kotlin
urkay-19 小时前
Android getDrawingCache 过时废弃
android·java·开发语言·kotlin·iphone·androidx
用户69371750013841 天前
24.Kotlin 继承:调用超类实现 (super)
android·后端·kotlin
alexhilton1 天前
借助RemoteCompose开发动态化页面
android·kotlin·android jetpack
QING6182 天前
Jetpack Compose Brush API 简单使用实战 —— 新手指南
android·kotlin·android jetpack
QING6182 天前
Jetpack Compose Brush API 详解 —— 新手指南
android·kotlin·android jetpack
鹿里噜哩2 天前
Spring Authorization Server 打造认证中心(二)自定义数据库表
spring boot·后端·kotlin
用户69371750013842 天前
23.Kotlin 继承:继承的细节:覆盖方法与属性
android·后端·kotlin
Haha_bj2 天前
五、Kotlin——条件控制、循环控制
android·kotlin
Kapaseker2 天前
不卖课,纯干货!Android分层你知多少?
android·kotlin