【问题标题】:Return a function (that returns a string) inside a function with kotlin使用 kotlin 在函数内部返回一个函数(返回一个字符串)
【发布时间】:2021-08-02 15:05:07
【问题描述】:

我试图在函数内部返回一个函数(返回一个字符串),但是,因为我没有明确说明(我不知道如何让它知道它会返回一个函数),结果我得到了 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 内部的字符串。我怎样才能做到这一点?谢谢。

【问题讨论】:

  • 你是要返回一个函数,还是内部函数产生的值
  • @amanin 我基本上是在尝试返回内部函数生成的字符串,但该函数需要存在(它是任务所必需的)。
  • 它返回Unit,因为这是块函数的默认值(主体在{ } 中)并且您不是return 值。你正在调用你的函数并得到一个String,但你没有对它们做任何事情。您需要在这些函数调用之前放置 return(然后它会抱怨,因为您需要添加 String 作为返回类型 - 默认情况下它期望 Unit 记住,即不返回任何内容)

标签: kotlin


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

示例(可以执行here):

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

上面的sn-p打印:

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 函数)。

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 2012-03-30
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多