gpt4 book ai didi

generics - Kotlin - 如何实现具有高阶函数作为泛型参数的类

转载 作者:行者123 更新时间:2023-12-02 02:43:21 24 4
gpt4 key购买 nike

我想实现一个泛型类,该类将任意参数类型的函数作为泛型参数类型。

我有一个骨架实现:

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>接口(interface),也许我可以用它来制作我的类(class) Action<T: FunctionN<Unit>>但是我该如何实例化我的对象呢?因为object: Action<() -> Unit>让编译器提示

最佳答案

Kotlin 至少具有以下在这种情况下似乎有用的功能:

  1. Kotlin 对元组有一些支持(PairTriple、...)
  2. Kotlin 对采用元组的 lambda 具有很好的解构语法
  3. 有一个 Unit 类型,它有 Unit 值作为唯一值:这允许抽象扩展到不需要参数的情况(Unit 在某种意义上是“零元”元组)

总的来说,这些功能允许您抽象回调,将任意类型 T 作为单个参数,并返回一个 Unit:

interface ObservableBooleanValue {
fun get(): Boolean
}

data class SimpleBooleanProperty(val value: Boolean) : ObservableBooleanValue {
override fun get(): Boolean = value
}

data class Point(val x: Int, val y: Int)
data class Color(val isBlack: Boolean) // otherwise white.

abstract class Action<T> {
internal abstract val performable: ObservableBooleanValue
internal abstract val perform: (T) -> Unit

operator fun invoke(settings: T) =
if (performable.get()) perform(settings)
else println("Cannot Perform")
}

object SomewhereElse {

private val install = object : Action<Triple<Int, Int, Point>>() {
override val performable: ObservableBooleanValue = SimpleBooleanProperty(true)
override val perform: (Triple<Int, Int, Point>) -> Unit =
{ (color, shape, point) ->
println("Color: $color, Shape: $shape, Point: $point")
}
}


private val delete = object : Action<Unit>() {
override val performable: ObservableBooleanValue = SimpleBooleanProperty(true)
override val perform = { _: Unit ->
println("Deleting")
}
}

}

它至少可以编译。我没有理由不认为它会同样出色地运行。

关于generics - Kotlin - 如何实现具有高阶函数作为泛型参数的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57726449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com