kotlin 返回类型:在'println()'外部调用Vs内部的函数

nkhmeac6  于 2022-12-30  发布在  Kotlin
关注(0)|答案(1)|浏览(184)

我刚到Kotlin。
我对匿名函数进行了一些试验,直到使用不同的方法面对同一概念的不同输出。

      • 第一个:**创建匿名函数:
var greetingFunction = { playerName: String , numBuildings: Int ->
    val currentYear = 2022
    println("Adding $numBuildings houses")
    "Welcome to SimVillage, $playerName! (Copyright $currentYear)\n"
}
      • 第二个:**创建一个函数,该函数将另一个函数作为参数:
private fun runSimulation(playerName: String, greetingFunc: (String, Int) -> String){
    val numOfBuildings = (1..3).shuffled().last()
    println(greetingFunc(playerName, numOfBuildings))
}
    • A-匿名函数的常规调用:**
println(runSimulation("Ahmed", greetingFunction))

输出:

Adding 3 houses
Welcome to SimVillage, Ahmed! (Copyright 2022)
    • B-匿名函数的速记调用:**
println(runSimulation("Different") { playerName: String , numBuildings: Int ->
    val currentYear = 2022
    println("Adding $numBuildings houses")
    "Welcome to SimVillage, $playerName! (Copyright $currentYear)\n"
})

输出:

Adding 2 houses
Welcome to SimVillage, Different! (Copyright 2022)

kotlin.Unit

我尝试删除println()并直接调用runSimulation函数,输出为:
输出:

Adding 2 houses
Welcome to SimVillage, Different! (Copyright 2022)

我真正想知道的是:我首先是如何使用速记语法得到"kotlin.unit"的打印结果的?

watbbzwu

watbbzwu1#

Kotlin会自动推断lambda表达式的类型,因为greetingFunction的最后一行是String

var greetingFunction = { playerName: String , numBuildings: Int ->
    val currentYear = 2022
    println("Adding $numBuildings houses")

    // the last line is a string -> Kotlin will infer that the return type is a String
    "Welcome to SimVillage, $playerName! (Copyright $currentYear)\n"
}

推断的类型是

var greetingFunction: (String, String) -> String

块体函数的返回类型是 * 非 * 推断的。如果函数没有返回有用的值,则其返回类型是Unit。函数

private fun runSimulation(playerName: String, greetingFunc: (String, Int) -> String) {
    val numOfBuildings = (1..3).shuffled().last()
    println(greetingFunc(playerName, numOfBuildings))
}

将返回Unit,因此

println(runSimulation("foo") { _, _ -> "bar" })

将打印runSimulation()的 * 返回 * 值,Unit.toString()kotlin.Unit
由于runSimulation()也将打印到stdout,因此这实际上与运行

println(println("bar"))

首先,“内部”println()将输出bar,然后“外部”println()将打印kotlin.Unit

bar
kotlin.Unit

相关问题