Lau*_*ves 6 kotlin recursive-type
我有代表流程中步骤的函数.每个函数也知道下一步,如果有的话.我希望能够做到这样的事情:
fun fooStep() : Step? {
... do something ...
return ::barStep // the next step is barStep
}
Run Code Online (Sandbox Code Playgroud)
这些函数是从中央调度函数调用的,它包含的代码有点像这样:
var step = startStep
while (step != null) {
step = step()
}
Run Code Online (Sandbox Code Playgroud)
请注意,特定步骤中的逻辑也决定了下一步,如果有的话.
我以为我可以定义Step为:
typealias Step = () -> Step?
Run Code Online (Sandbox Code Playgroud)
所以a Step是一个返回另一个的函数Step,或者为null.但是,这无法编译:
Kotlin: Recursive type alias in expansion: Step
Run Code Online (Sandbox Code Playgroud)
我可以通过将函数包装在一个对象中来解决这个问题.例如:
data class StepWrapper(val step: () -> StepWrapper?)
Run Code Online (Sandbox Code Playgroud)
并相应地更改我的功能签名.
不幸的是,这意味着我不能只使用函数文字(例如:) ::barStep,而是必须将它们包装在StepWrapper:
fun fooStep() : StepWrapper? {
... do something ...
return StepWrapper(::barStep)
}
Run Code Online (Sandbox Code Playgroud)
(我也必须相应地更改我的调度循环.)
如果可能的话,我想避免创建这些包装器对象的需要.在Kotlin有什么办法吗?
您可以使用一些通用接口来定义它:
interface StepW<out T> : ()->T?
interface Step : StepW<Step>
class Step1 : Step {
override fun invoke(): Step? = Step2()
}
class Step2 : Step {
override fun invoke(): Step? = null
}
Run Code Online (Sandbox Code Playgroud)
Step你的递归函数类型在哪里。
| 归档时间: |
|
| 查看次数: |
639 次 |
| 最近记录: |