【发布时间】:2021-02-14 04:16:49
【问题描述】:
如何编写一个 Kotlin 泛型函数,将函数作为参数并为其添加副作用?例如,
fun something(one: Int, two: String): String { return "${one}, ${two}" }
fun somethingElse(arg: Array<String>): String { return "${arg}" }
val w1 = wrapped(::something)
w1(42, "hello")
val w2 = wrapped(::somethingElse)
w2(arrayOf("ichi", "ni"))
以下适用于仅采用单个参数的函数:
fun <A, R> wrapped(theFun: (a: A) -> R): (a: A) -> R {
return { a: A ->
theFun(a).also { println("wrapped: result is $it") }
}
}
要使用任意数量的参数,我需要一些结构来提供参数列表的类型。不幸的是,不能使用 Function 泛型,因为它只需要一个参数。以下不编译:
fun <A, R> wrapped(theFun: Function<A, R>): Function<A, R> {
return { args: A ->
theFun(*args).also { println("wrapped: result is ${it}") }
}
}
或者我可以使用varargs?似乎不适用于 lambda。还是 Kotlin 反射?
【问题讨论】:
-
只能通过反射实现。
-
老兄,请为接受的答案投票!
标签: kotlin generics lambda delegation side-effects