How to create abstract Function using java 8

Viewed 333

I am trying to implement a pipeline design pattern using Java 8 with the below article for my reference:

https://stackoverflow.com/a/58713936/4770397

Code:

public abstract class Pipeline{
Function<Integer, Integer> addOne = it -> {
        System.out.println(it + 1);
        return it + 1;
    };

Function<Integer, Integer> addTwo = it -> {
        System.out.println(it + 2);
        return it + 2;
    };

Function<Integer, Integer> timesTwo = input -> {
        System.out.println(input * 2);
        return input * 2;
    };

final Function<Integer, Integer> pipe = sourceInt
    .andThen(timesTwo)
    .andThen(addOne)
    .andThen(addTwo);
}

I am trying to add one abstract method & want to override it.
I am trying to do something like:

abstract BiFunction<Integer, Integer,Integer> overriden; 

and change pipe to:

final Function<Integer, Integer> pipe = sourceInt
    .andThen(timesTwo)
    .andThen(overriden)
    .andThen(addOne)
    .andThen(addTwo);
}

But the problem is, I don't know to declare a Function<Integer, Integer> as an abstract method.

2 Answers

You can just declare a regular abstract method that takes an Integer and returns an Integer and use the method reference syntax to refer to it:

public abstract Integer overridden(Integer input);

final Function<Integer, Integer> pipe = sourceInt
    .andThen(timesTwo)
    .andThen(this::overridden)
    .andThen(addOne)
    .andThen(addTwo);

Fields aren't a subject to polymorphism - you need a method. You either write

  1. a method that just returns a Function<Integer, Integer> instance

    public abstract Function<Integer, Integer> getMyFunction();
    
  2. a method that actually represents a Function<Integer, Integer>

    public abstract Integer myFunction(Integer i);
    

and then do

.andThen(getMyFunction())

or

.andThen(i -> myFunction(i))
// .andThen(this::myFunction) // fancier

respectively.

For example,

interface I {
  Function<Integer, Integer> getFunction();
  Integer function(Integer i);
}

class A implements I {
  @Override
  public Function<Integer, Integer> getFunction() {
    return i -> i + 1;
  }

  @Override
  public Integer function(Integer i) {
    return i + 1;
  }
}

class B implements I {
  @Override
  public Function<Integer, Integer> getFunction() {
    return i -> i * 2;
  }

  @Override
  public Integer function(Integer i) {
    return i * 2;
  }
}

class T {
  public static void main(String[] args) {
    A a = new A();
    B b = new B();

    Function<Integer, Integer> f1 = a.getFunction().andThen(b.getFunction());
    System.out.println(f1.apply(2)); // 6

    Function<Integer, Integer> f2 = a.getFunction().andThen(b::function);
    System.out.println(f2.apply(2)); // 6

    Function<Integer, Integer> f3 = ((Function<Integer, Integer>)a::function).andThen(b::function);
    System.out.println(f3.apply(2)); // 6
  }
}
Related