【发布时间】:2019-08-30 12:06:08
【问题描述】:
我想实现一个泛型类,它将任意数量的函数作为泛型参数类型。
我有一个骨架实现:
abstract class Action<T> {
internal abstract val performable: ObservableBooleanValue
internal abstract val perform: T
}
还有几个对象:
private val install = object : Action<(Int, Int, Point) -> Unit>() {
override val performable: ObservableBooleanValue = SimpleBooleanProperty(true)
override val perform = { color: Int, shape: Int, point: Point ->
println("Color: $color, Shape: $shape, Point: $point")
}
operator fun invoke(color: Int, shape: Int, point: Point) =
if (performable.get()) perform(color, shape, point)
else println("Cannot Perform")
}
private val delete = object : Action<() -> Unit>() {
override val performable: ObservableBooleanValue = SimpleBooleanProperty(true)
override val perform = {
println("Deleting")
}
operator fun invoke() =
if (performable.get()) perform()
else println("Cannot Perform")
}
我将拥有更多这样的对象,并希望将invoke 函数作为Action 类的成员,这样我就不必为每个对象都实现它。
我想实现这样的目标:
abstract class Action<T> {
...
operator fun invoke(???) =
if (performable.get()) perform(???)
else println("Cannot Perform")
}
这可能吗?
我查看了一些文档并找到了一个FunctionN<out R> 接口,也许我可以用它来创建我的类Action<T: FunctionN<Unit>> 但是我如何实例化我的对象?因为object: Action<() -> Unit> 让编译器抱怨
【问题讨论】:
-
当你不知道arity时,你将如何传递参数来调用? (你能不能有一个有趣的参数数组??)
标签: generics kotlin higher-order-functions