首页 > 解决方案 > 使用 kotlin 在函数内部返回一个函数(返回一个字符串)

问题描述

我试图在函数内部返回一个函数(返回一个字符串),但是,因为我没有明确说明(我不知道如何让它知道它会返回一个函数),结果我得到了 kotlin.Unit 。

这是功能:

fun takeOutArticle(code:String) {

       fun onSuccess(finalPrice: Int): String {
           return "Your price is $finalFee."
       }

       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())

           onSuccess(finalPrice)
       } else {
           onError()
       }

因此,当我调用该函数时,无论它是否成功,它都会返回单位,但我需要它返回 onSuccess 或 onError 内部的字符串。我怎样才能做到这一点?谢谢你。

标签: kotlin

解决方案


  1. 从函数返回值时,您必须在函数签名中指定返回类型(在名称和参数之后)。来源:函数语法
  2. 除了 lambdas,您还需要在返回值/表达式前面添加一个 return 关键字。请注意,这if/else是一个表达式。
  3. 请注意,您可以返回内部函数的结果,但请注意您的措辞,因为在 Kotlin 中,您还可以返回对函数的引用

示例(您可以在此处执行):

import kotlin.random.Random

fun doStuff() : String {
    fun resultIfTrue() : String { return "Returns True" }
    fun resultIfFalse() : String { return "Returns False" }
    
    return if (Random.nextBoolean()) {
        resultIfTrue()
    } else {
        resultIfFalse()
    }
}

fun deferStuff() : () -> String {
    fun resultIfTrue() : String { return "Returns True"; }
    fun resultIfFalse() : String { return "Returns False"; }
    
    return if (Random.nextBoolean()) {
        ::resultIfTrue
    } else {
        ::resultIfFalse
    }
}

fun main() {
    println("Return result of inner function")
    for (i in 0 until 4) println(doStuff())
    println("Return inner function")
    for (i in 0 until 4) {
        val fn = deferStuff()
        println("Function returned another function: $fn that must be executed: ${fn()}")
    }
}

上面的代码段打印:

Return result of inner function
Returns False
Returns False
Returns True
Returns True
Return inner function
Function returned another function: function resultIfFalse (Kotlin reflection is not available) that must be executed: Returns False
Function returned another function: function resultIfFalse (Kotlin reflection is not available) that must be executed: Returns False
Function returned another function: function resultIfFalse (Kotlin reflection is not available) that must be executed: Returns False
Function returned another function: function resultIfTrue (Kotlin reflection is not available) that must be executed: Returns True

您可以看到输出的前半部分直接显示了内部函数生成的值,因为它们是doStuff直接从内部调用的。

然而,在第二种情况下,我们返回了内部函数本身,它需要由用户(这里是main函数)稍后调用。


推荐阅读