在 Kotlin 中将元组或三元组作为参数传递
Passing a Tuple or Triple as parameters in Kotlin
我在 Kotlin 中有一个函数是这样的:
fun getSlots(year: Int, month: Int, day: Int) {
// some magic stuff, for example let's just print it
print("$year-$month-$day")
}
我还有另一个函数 return 是 Triple
:
fun myMagicFunction(): Triple<Int, Int, Int> {
return Triple(2020, 1, 1)
}
我想调用第一个函数 getSlots
,使用第二个函数 myMagicFunction
的 return 值,而不必从三元组中提取成员并传递它们逐个。例如,在 Python 中,可以通过 func(*args)
实现,但我不知道在 Kotlin 中是否可行。
在 Kotlin 中有可能吗?还是我必须在这种情况下走慢路?假设将前两个函数修改为 return 其他内容不是一个选项。
我找不到任何简单的方法(希望有一天它能在 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()
当然你可以再添加一对:
infix fun <T, U, V> KFunction2<T, U, V>.callWith(arguments: Pair<T, U>) : V = this.call(*arguments.toList().toTypedArray())
编辑:
感谢@broot 我们有更好的解决方案:
infix fun <T, U, S, V> ((T, U, S) -> V).callWith(arguments: Triple<T, U, S>) : V = this(arguments.first, arguments.second, arguments.third)
Kotlin 也有一个扩展运算符 (func(*args)
),但目前它仅在 func
的参数声明为 vararg
时有效(以避免运行时异常,如果args
与 func
arity 不同)。
再添加一行带有析构声明的代码:
val (year, month, day) = myMagicFunction()
getSlots(year, month, day)
我在 Kotlin 中有一个函数是这样的:
fun getSlots(year: Int, month: Int, day: Int) {
// some magic stuff, for example let's just print it
print("$year-$month-$day")
}
我还有另一个函数 return 是 Triple
:
fun myMagicFunction(): Triple<Int, Int, Int> {
return Triple(2020, 1, 1)
}
我想调用第一个函数 getSlots
,使用第二个函数 myMagicFunction
的 return 值,而不必从三元组中提取成员并传递它们逐个。例如,在 Python 中,可以通过 func(*args)
实现,但我不知道在 Kotlin 中是否可行。
在 Kotlin 中有可能吗?还是我必须在这种情况下走慢路?假设将前两个函数修改为 return 其他内容不是一个选项。
我找不到任何简单的方法(希望有一天它能在 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()
当然你可以再添加一对:
infix fun <T, U, V> KFunction2<T, U, V>.callWith(arguments: Pair<T, U>) : V = this.call(*arguments.toList().toTypedArray())
编辑: 感谢@broot 我们有更好的解决方案:
infix fun <T, U, S, V> ((T, U, S) -> V).callWith(arguments: Triple<T, U, S>) : V = this(arguments.first, arguments.second, arguments.third)
Kotlin 也有一个扩展运算符 (func(*args)
),但目前它仅在 func
的参数声明为 vararg
时有效(以避免运行时异常,如果args
与 func
arity 不同)。
再添加一行带有析构声明的代码:
val (year, month, day) = myMagicFunction()
getSlots(year, month, day)