如何创建';然后';作为Kotlin中泛型类上可组合性的中缀运算符?

如何创建';然后';作为Kotlin中泛型类上可组合性的中缀运算符?,kotlin,functional-programming,Kotlin,Functional Programming,问题陈述:我正在尝试重新创建Scala/Finagle的,然后方法链接/组合跨两种类型:过滤器和服务 目标是能够做到以下几点: val f1 = Filter1() val f2 = Filter2() val s3 = Service3() val pipeline = f1 andThen f2 andThen s3 val result = pipeline(4) //execute pipeline with integer value of 4 过滤器应该可以与其他过滤器组合,

问题陈述:我正在尝试重新创建Scala/Finagle的
,然后
方法链接/组合跨两种类型:过滤器和服务

目标是能够做到以下几点:

val f1 = Filter1()
val f2 = Filter2()
val s3 = Service3()

val pipeline = f1 andThen f2 andThen s3 

val result = pipeline(4) //execute pipeline with integer value of 4
过滤器应该可以与其他过滤器组合,也可以是“结束一条链”的服务。服务还应该可以与其他服务组合。两者似乎都会导致
未解析的引用,然后

现有的非工作解决方案:

typealias Transformer<A,B> = (A) -> B

abstract class Service<A,B>: Transformer<A,B> {

    //DOESN'T WORK
    infix fun <A,B,C> Service<A,B>.andThen(f: Service<B,C>): Service<A,C> {
        val left = this
        return object : Service<A, C>() {
            override fun invoke(p1: A): C {
                return f(left.invoke(p1))
            }
        }
    }
}

typealias TwoWayTransformer<A,B,C,D> = (A, Service<C,D>) -> B

abstract class Filter<A,B,C,D>: TwoWayTransformer<A,B,C,D> {

    //DOESN'T WORK
    infix fun <A,B,E,F> Filter<A,B,C,D>.andThen(next: Filter<C,D,E,F>): Filter<A,B,E,F> {
        val left = this
        return object: Filter<A,B,E,F>() {
            override fun invoke(a: A, service: Service<E,F>): B {
                val s = object: Service<C,D>() {
                    override fun invoke(c: C): D { return next.invoke(c,service) }
                }

                return left.invoke(a,s)
            }
        }
    }

    //DOESN'T WORK
    infix fun <A,B,C,D> Filter<A,B,C,D>.andThen(next: Service<C,D>): Service<A,B> {
        val left = this
        return object: Service<A,B>() {
            override fun invoke(a: A): B {
                return left.invoke(a, next)
            }
        }
    }
}

typealias Transformer

您需要的签名是

infix fun <C> andThen(f: Service<B,C>): Service<A,C>
infix fun <E,F> andThen(next: Filter<C,D,E,F>): Filter<A,B,E,F>
infix fun andThen(next: Service<C,D>): Service<A,B>
infix-fun然后(f:Service):Service
中缀有趣,然后(下一个:过滤器):过滤器
中缀乐趣第二(下一步:服务):服务

切勿向类定义中已声明的函数添加任何类型变量。永远不要为类本身添加额外的接收器。

您需要的签名是

infix fun <C> andThen(f: Service<B,C>): Service<A,C>
infix fun <E,F> andThen(next: Filter<C,D,E,F>): Filter<A,B,E,F>
infix fun andThen(next: Service<C,D>): Service<A,B>
infix-fun然后(f:Service):Service
中缀有趣,然后(下一个:过滤器):过滤器
中缀乐趣第二(下一步:服务):服务

切勿向类定义中已声明的函数添加任何类型变量。永远不要为类本身添加额外的接收器。

Aaah!我懂了。这是我在科特林的第10天,我非常想念Scala时代的一些东西。我做出了改变,并高兴地报告它起了作用。谢谢你啊!我懂了。这是我在科特林的第10天,我非常想念Scala时代的一些东西。我做出了改变,并高兴地报告它起了作用。多谢各位_/\_