我在 Kotlin 中有一個類似這樣的函式:
fun getSlots(year: Int, month: Int, day: Int) {
// some magic stuff, for example let's just print it
print("$year-$month-$day")
}
我還有另一個回傳 a 的函式Triple:
fun myMagicFunction(): Triple<Int, Int, Int> {
return Triple(2020, 1, 1)
}
我想呼叫第一個函式getSlots,使用第二個函式的回傳值myMagicFunction,而不必從三元組中提取成員并逐個傳遞它們。例如,在 Python 中可以通過執行func(*args),但我不知道在 Kotlin 中是否可行。
在 Kotlin 中可能嗎,還是我必須在這種情況下慢慢來?假設修改前兩個函式以回傳其他內容不是一種選擇。
uj5u.com熱心網友回復:
我找不到任何簡單的方法(希望有一天它會在 kotlin 中可用)。但是,您可以撰寫一些輔助中綴函式,如下所示:
infix fun <T, U, S, V> KFunction3<T, U, S, V>.callWith(arguments: Triple<T, U, S>) : V = this.call(*arguments.toList().toTypedArray())
然后只需簡單地呼叫它:
::getSlots callWith myMagicFunction()
當然,您可以為 Pair 添加另一個:
infix fun <T, U, V> KFunction2<T, U, V>.callWith(arguments: Pair<T, U>) : V = this.call(*arguments.toList().toTypedArray())
uj5u.com熱心網友回復:
Kotlin 也有一個擴展運算子 ( func(*args)),但目前它只有在引數 offunc宣告為時才有效(如果 ofvararg的大小args與funcarity不同,則避免運行時例外)。
只需添加一行帶有破壞宣告的代碼:
val (year, month, day) = myMagicFunction()
getSlots(year, month, day)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312842.html
上一篇:在Kotlin資料類中更新資料
