kotlin - 使用 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 内部的字符串。我怎样才能做到这一点?谢谢你。
解决方案
- 从函数返回值时,您必须在函数签名中指定返回类型(在名称和参数之后)。来源:函数语法。
- 除了 lambdas,您还需要在返回值/表达式前面添加一个 return 关键字。请注意,这
if/else
是一个表达式。 - 请注意,您可以返回内部函数的结果,但请注意您的措辞,因为在 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
函数)稍后调用。
推荐阅读
- ios - 快速将数据附加到不同视图控制器中的数组中
- python - 在 Azure Databricks 中一次删除多个表
- c# - 如何在 BUnit 中使用继承的 TestContext 添加测试授权?
- python - 从气流中的 dag 配置中为 dag 分配 start_date
- flutter - 在 Flutter 中按下返回时键盘会闪烁
- javascript - 将数组转换为 json 的最佳选择是什么
- python - 使用 Python Selenium 获取当前名称
- c++ - CMake:如何检查是否使用 -stdlib=libc++ 编译了 STATIC 库?
- macros - 在 Inno Setup [Code] 部分中将宏扩展为 Pascal 代码
- istio - istio-ingressgateway 总是等待 Istio Pilot 信息