首页 文章

什么时候可以在Kotlin中省略返回类型

提问于
浏览
4

我在Kotlin中有以下功能:

fun max(a: Int, b: Int): Int {
    return if (a > b) a else b
}

这可以简化为:

fun max(a: Int, b: Int) = if (a > b) a else b

在前面的定义中,函数的返回类型已被省略,这被称为表达式主体 . 我想知道是否存在其他可以在Kotlin中省略函数的返回类型的情况 .

3 回答

  • 1

    具有块体的函数必须始终明确指定返回类型,除非它们用于返回Unit .

    如果函数未返回任何有用的值,则其返回类型为 Unit . Unit 是只有一个值的类型 - 单位 . 不必显式返回此值

    fun printHello(name: String?): Unit {
        if (name != null)
            println("Hello ${name}")
        else
            println("Hi there!")
        // `return Unit` or `return` is optional
    }
    

    Unit 返回类型声明也是可选的 . 上面的代码相当于

    fun printHello(name: String?) {
        ...
    }
    
  • 2

    当返回类型是 Unit

    fun printHello(): Unit {
        print("hello")
    }
    

    是相同的

    fun printHello() {
        print("hello")
    }
    

    也是,是一样的

    fun printHello() = print("hello")
    
  • 1

    通常,函数必须声明它的返回类型 . 但是如果某些函数由单个表达式组成,那么我们可以省略大括号和返回类型,并在表达式之前使用 = 符号而不是return关键字 . 这种类型的函数称为 Single Expression Functions .

    Example:

    fun add(a: Int, b: Int): Int {
        return a + b
    }
    

    此代码可以简化为:

    fun add(a: Int, b: Int) = a + b
    

    编译器会强制您执行此操作 .

相关问题