我试图在函数内部返回一个函数(返回一个字符串),但是,因为我没有明确说明(我不知道如何让它知道它会返回一个函数),结果我得到了 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()
}
因此,当我调用该函数以及它是否成功时,它会返回 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()}")
}
}
上面的代码片段打印:
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
函数)调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句