我试图在函数内部返回一个函数(返回一个字符串),但是,由于我没有明确说明这一点(我不确定如何制作它以便函数知道它将返回一个函数),结果我得到了 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()
}
Run Code Online (Sandbox Code Playgroud)
因此,当我调用该函数时,无论它是否成功,它都会返回 unit,但我需要它返回 onSuccess 或 onError 内部的字符串。我怎样才能做到这一点?谢谢。
if/else是一个表达式。示例(您可以在此处执行):
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()}")
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码片段打印:
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
Run Code Online (Sandbox Code Playgroud)
您可以看到输出的前半部分直接显示了内部函数生成的值,因为它们是doStuff直接从内部调用的。
然而,在第二种情况下,我们返回了内部函数本身,它需要稍后由用户调用(这里是函数main)。
| 归档时间: |
|
| 查看次数: |
2717 次 |
| 最近记录: |