是否可以在Kotlin中创建递归函数类型? [英] Is it possible to create a recursive function type in Kotlin?

查看:103
本文介绍了是否可以在Kotlin中创建递归函数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有代表流程中各个步骤的功能.每个功能也知道下一步(如果有的话).我希望能够执行以下操作:

I have functions that represent steps in a process. Each function also knows the next step, if there is one. I'd like to be able to do something like:

fun fooStep() : Step? {
    ... do something ...
    return ::barStep // the next step is barStep
}

这些函数是从中央分派函数调用的,该函数包含如下代码:

These functions are called from a central dispatching function, which contains code a bit like this:

var step = startStep
while (step != null) {
    step = step()
}

请注意,即使有一个步骤,特定步骤中的逻辑也会确定下一步.

Note that the logic in a particular step also determines the next step, if there even is one.

我认为我可以将Step定义为:

I thought I could define Step as:

typealias Step = () -> Step?

因此,Step是返回另一个Step的函数,或者为null.但是,这无法通过以下方式进行编译:

So a Step is a function that returns another Step, or null. However, this fails to compile with:

Kotlin: Recursive type alias in expansion: Step

我可以通过将函数包装在对象中来解决此问题.例如:

I can work around this by wrapping the function in an object. eg:

data class StepWrapper(val step: () -> StepWrapper?)

并相应地更改我的功能签名.

and changing my function signatures accordingly.

不幸的是,这意味着我不能只使用函数文字(例如:::barStep),而必须将它们包装在StepWrapper中:

Unfortunately, this means that I cannot just use function literals (eg: ::barStep), but instead have to wrap them in a StepWrapper:

fun fooStep() : StepWrapper? {
    ... do something ...
    return StepWrapper(::barStep)
}

(我还必须相应地更改调度循环.)

(I also have to change my dispatch loop, accordingly.)

如果可能的话,我希望避免创建这些包装对象.在Kotlin中有什么方法可以做到这一点?

I'd like to avoid the need to create these wrapper objects, if possible. Is there any way to do this in Kotlin?

推荐答案

您可以使用一些通用接口进行定义:

You can define it by using some generic interface:

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
}

其中Step是您的递归函数类型.

Where Step is your recursive function type.

这篇关于是否可以在Kotlin中创建递归函数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆