You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin外层函数如何返回内部嵌套函数的String结果而非Unit类型

问题原因

Kotlin中使用代码块体的函数如果不显式声明返回类型,默认返回Unit类型,且你没有显式将两个分支的内部函数执行结果作为外层函数的返回值返回,因此最终得到的结果始终是Unit。另外你代码里还存在一处变量名不匹配的问题:onSuccess函数的参数名为finalPrice,但返回字符串里引用的是未定义的finalFee,会触发编译错误。

解决方法
  • 给外层takeOutArticle函数显式声明返回类型为String
  • 在onSuccess、onError的调用前添加return关键字,将内部函数的返回值作为外层函数的结果返回
  • 修正onSuccess里的变量名拼写错误
修改后的完整代码
// 显式声明返回类型为String
fun takeOutArticle(code:String): String {

       fun onSuccess(finalPrice: Int): String {
           // 修正变量名不匹配问题,将finalFee替换为参数名finalPrice
           return "Your price is $finalPrice."
       }

       fun onError(): String {
           return "Error."
       }

       val articlesCode = house.articles.find{ it.code == code }
       if (articlesCode != null) {
           val finalPrice = calculatePrice(
               articleType = articlesCode.articleCode,
               finalTime = articlesCode.finalTime.toInt(),
               hasCard = !articlesCode.Card.isNullOrEmpty())
           // 加return将内部函数结果作为外层函数返回值
           return onSuccess(finalPrice)
       } else {
           // 加return将内部函数结果作为外层函数返回值
           return onError()
       }
}
可选优化写法

你也可以把外层函数改为表达式体写法,Kotlin会自动推导返回类型,可省略显式的返回类型声明和分支return:

fun takeOutArticle(code:String) = run {
    fun onSuccess(finalPrice: Int) = "Your price is $finalPrice."
    fun onError() = "Error."

    val articlesCode = house.articles.find{ it.code == code }
    if (articlesCode != null) {
        val finalPrice = calculatePrice(
            articleType = articlesCode.articleCode,
            finalTime = articlesCode.finalTime.toInt(),
            hasCard = !articlesCode.Card.isNullOrEmpty())
        onSuccess(finalPrice)
    } else {
        onError()
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 09:45:04