Passing a Java reference to a method that returns a value to a single returning `void`

The JLS casting rules seem rather complicated in this question: is it correct to refer to a method that returns a certain value, to a link that accepts the same types of arguments but returns void? I think this is normal, because voidnarrower than any type.

For instance...

import java.util.function.Consumer;

public class MethodRefCaster {

  /** Operation accepting and returning Integer. */
  Integer fooOp(Integer x) {
    System.out.println(x);
    return x + 3;
  }

  /** Applier of given op accepting Integer, returning void. */
  void applyOpToBar(Consumer<Integer> op, int bar) {
    op.accept(bar);
  }

  public static void main(String [] args) {
    MethodRefCaster x = new MethodRefCaster();

    // Cast the method ref to make it fit.
    x.applyOpToBar((Consumer<Integer>) x::fooOp, 42);
  }
}

This prints 42, as you might expect. But is Java correct? Many thanks.

+4
source share

Source: https://habr.com/ru/post/1693292/


All Articles