【发布时间】:2021-10-12 19:39:40
【问题描述】:
我想拥有例如:
class Foo {
fun doSomething(arg1: String, arg2: String, arg3: Boolean)
}
class FooDelegate {
//different fun name
fun execute by Foo::doSomething
}
反射或其他方式。
我目前拥有的是:
class FooDelegated<R>(
private val func: KFunction<R>
) {
fun execute(vararg params: Any) = func.call(*params)
}
这样我就可以打电话了
FooDelegated(Foo::doSomething).execute("1", "2", true)
但是我需要发送不知道的参数。我希望我的编译器知道可以发送哪些参数。否则,我可以编写以下内容,直到运行时才会失败:
FooDelegated(Foo::doSomething).execute("1", "2", "new argument", false)
请注意,我希望它具有不同的名称,而不是使用接口。
【问题讨论】:
-
fun execute by Foo::doSomething将如何工作?你甚至没有Foo的实例!您是否期望execute采用Foo的额外参数? -
另外,
fun execute(arg1: String, arg2: String, arg3: Boolean) = someFoo.doSomething(arg1, arg2, arg3)有什么问题? -
我想不出任何可能的方法在编译时使用注释来做到这一点。反射是无用的,因为它是在运行时完成的。我认为你需要一个定制的 Kotlin 编译器来实现这一点。
标签: kotlin generics parameter-passing kotlin-reflect kotlin-delegate