传递Tuple或Triple作为Kotlin的参数



我在Kotlin中有一个函数,它是这样的:

fun getSlots(year: Int, month: Int, day: Int) {
// some magic stuff, for example let's just print it
print("$year-$month-$day")
}

我有另一个返回Triple的函数:

fun myMagicFunction(): Triple<Int, Int, Int> {
return Triple(2020, 1, 1)
}

我想getSlots调用第一个函数,使用第二个函数的返回值myMagicFunction,无需提取三,将他们的成员一个接一个。例如,在Python中可以通过做func(*args)来实现,但我不知道在Kotlin中是否可能。

在Kotlin中是否可能,或者我是否必须在这种情况下走慢路?假设不能修改前两个函数以返回其他内容。

我找不到任何简单的方法(希望有一天它将在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())

编辑:多亏了@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的大小不同而导致运行时异常)。

只需再添加一行带有析构声明的代码:

val (year, month, day) = myMagicFunction()
getSlots(year, month, day)

最新更新