Kotlin 函数输出类型

136 阅读2分钟

一、基础语法规则

  1. 显式声明方式

    fun sum(a: Int, b: Int): Int { // 显式声明返回 Int 类型 :ml-citation{ref="8" data="citationList"}
        return a + b
    }
    
    • 函数定义时在参数列表后通过 : 类型 指定返回值类型
    • 无返回值时可声明为 Unit(可省略)或完全省略返回类型声明 18
  2. 类型推断机制

    fun multiply(a: Int, b: Int) = a * b // 自动推断返回 Int 类型 :ml-citation{ref="6" data="citationList"}
    
    • 当函数体为单表达式时,编译器自动推断返回类型
    • 适用于简单逻辑场景,但复杂逻辑仍需显式声明 68

二、特殊返回值类型

类型特性示例
Unit表示无返回值(类似 Java 的 void)fun printMsg(msg: String): Unit { println(msg) } 18
Nothing表示函数永不返回(如抛出异常或无限循环)fun fail(): Nothing { throw Exception() } 3
函数类型可返回另一个函数fun createAdder(x: Int): (Int) -> Int { return { y -> x + y } }

三、案例解析

fun t01() { println(1)}  //默认Unit,除非我们制定类型
fun t02() { 3.1415926 }  //默认Unit
fun t03() { true}  //默认Unit
fun t04():String {return "haoran"}  //指定 Int
fun t05():Int {return 99 }  //默认Unit,除非我们制定类型
fun s01() = { }  // () -> 返回一个函数
fun s02() = { println("OK")}  //默认Unit,除非我们制定类型

fun s03() :Char = run {'A'} //Char  run 返回{}里面函数返回类型
fun s04(): ()->Boolean = {true}

run 函数的作用

run 是 Kotlin 标准库中的‌作用域函数‌,其行为特性为:

  1. 上下文对象‌:以 this 形式访问接收者对象(本例未显式指定接收者,默认使用顶级作用域)
  2. 返回值‌:返回 Lambda 表达式最后一行的结果(此处为字符 'A')8
  3. 空安全‌:若接收者为 null,直接返回 null(本例不涉及)

等效代码展开

上述代码等价于:

kotlinCopy Code
fun s03(): Char {
    return run {
        'A' // Lambda 的最后一行即返回值
    }
}

或更基础的实现:

kotlinCopy Code
fun s03(): Char {
    return 'A'
}
  • 使用 run 在此场景中未带来额外功能,仅为语法示例

典型应用场景对比

场景使用 run 的价值示例
对象初始化链式配置属性并返回结果Car().run { color = "red"; speed = 200; this }
空安全操作配合安全调用运算符 (?.) 处理可空对象user?.run { sendEmail() }
作用域隔离创建临时变量作用域避免命名污染run { val tmp = ...; ... }

与其他作用域函数对比

函数接收者访问方式返回值典型场景
runthisLambda 结果对象配置/计算
letitLambda 结果空安全检查
withthisLambda 结果非扩展函数作用域操作
applythis接收者对象本身对象初始化