javagenericstype-inference

How to define classes for several computation steps to use Type inference in Java?


How to change the code below to get type inference? The line

 Integer b = run().task1(()->555).task2((a)->a+5);

Does not compile, because compiler can't conclude that a is Integer.

class MyTest {

    @Test
    void testWithTwoTasks() {
            Integer b = run().task1(()->555).task2((a)->a+5);
    }

    public <T, R> MyTasksRunner<T, R> run() {
             return new MyTasksRunner<>();
    }

    public static class MyTasksRunner<T, R> {
         public MyStep1<T, R> task1(Callable<T> task1) {
             return new MyStep1<>(task1);
         }
    }

    public static class MyStep1<T,R>  {

         private Callable<T> step1;

         MyStep1 (Callable<T> task) {
            this.step1 = task;
         }

        public R task2(Function<T,R> task) throws Exception {
            return task.apply(step1.call());
        }
   }
}

Solution

  • Provide the type-parameters, for the run method.

    void testWithTwoTasks() throws Exception {
        Integer b = this.<Integer, Integer>run().task1(()->555).task2((a)->a+5);
    }