You need to enable JavaScript to run this app. Kotlin匿名函数简写调用为何输出kotlin.Unit?
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin匿名函数简写调用为何输出kotlin.Unit?

为什么Kotlin中用简写方式调用函数会输出kotlin.Unit?

问题回顾

你作为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. 常规传参调用(无kotlin.Unit输出):
runSimulation("Ahmed", greetingFunction)

输出:

Adding 3 houses
Welcome to SimVillage, Ahmed! (Copyright 2022)
  • B. 尾lambda简写调用(带kotlin.Unit输出):
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

原因分析

你看到的kotlin.Unit输出和简写调用方式无关,本质是两个核心点:

1. runSimulation的返回类型是Unit

Kotlin中,没有显式指定返回类型且函数体为代码块的函数,默认返回Unit——这是一种表示“无有效返回值”的类型,类似Java的void,但Unit是实际存在的对象。

2. println的作用是打印函数返回值

  • 当你直接调用runSimulation时:
    函数内部已经通过println(greetingFunc(...))输出了内容,函数返回的Unit没有被打印,所以不会出现kotlin.Unit。
  • 当你用println包裹runSimulation调用时:
    先执行runSimulation输出两行内容,然后println会打印runSimulation的返回值Unit,因此最后多了一行kotlin.Unit。

3. 简写方式本身不影响输出

不管是常规传参还是尾lambda简写,只要用println包裹runSimulation的调用,都会输出kotlin.Unit。比如把A改成带println的调用:

println(runSimulation("Ahmed", greetingFunction))

输出同样会包含kotlin.Unit;反之把B改成直接调用,就不会有额外的输出。

解决方式

如果不想输出kotlin.Unit,只需直接调用runSimulation,不要用println包裹它的调用即可,不管是哪种传参方式。

内容的提问来源于stack exchange,提问作者Ahmedx288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:10:33