将组合函数转换为Function的子类

问题描述 投票:2回答:1

这就是我想做的事情:

我希望有一个抽象类Operation实现Function接口,然后有像OpA继承它的子类。 Operation是从FunctionIntegerInteger,我希望能够使用Function.composeFunction.andThen来组成OpAs。在代码中:

public abstract class Operation implements Function<Integer, Integer>
{
    // ...
}
public class OpA extends Operation
{
    // ...
}
public class Main
{
    public static void main(String[] args)
    {
        OpA a = new OpA();
        OpA b = new OpA();

        // vvv Problem here vvv
        Operation compose = (Operation) a.andThen(b);
    }
}

问题是,尽管a.andThen(b)是从FunctionIntegerInteger,我不能把它投到Operation。在运行时抛出java.lang.ClassCastException

Caused by: java.lang.ClassCastException: java.util.function.Function$$Lambda$56/1571051291 cannot be cast to operation.Operation
at application.Main.main(Main.java:25)

说实话,我并不是真的希望它能像那样开始工作,但出于我的目的,我真的需要组合函数成为Operation。所以对于我的问题,我要求一种方法来使函数组合返回一个与Operation类型兼容的对象。任何有效的方法都很好:如果有必要的话,我愿意写自己的composedandThen功能(但我不知道怎么做),虽然总是很受欢迎。

java casting
1个回答
1
投票

好吧,如果你想要实现一个Sum,可以这样做:

static class Sum extends Operation {

    @Override
    public Integer apply(Integer x) {
        return x + 1;
    }

    public Operation andThen(Operation after) {
        return new Operation() {
            @Override
            public Integer apply(Integer x) {
                return after.apply(Sum.this.apply(x));
            }
        };
    }
}

打电话给:

Sum a = new Sum();
Sum b = new Sum();

Operation composed = a.andThen(b);
System.out.println(composed.apply(2)); // 4
© www.soinside.com 2019 - 2024. All rights reserved.