#Scope Resolution operator(::) in java?

1 messages · Page 1 of 1 (latest)

serene fjord
#

well I came across IO::println also Integer::parseInt also i wrote integer -> Instant.ofEpochSecond(integer) and intellij said it can be replaced with Instant::ofEpochSecond. I can see it's working like . operator but all of this i saw inside streams. How does that work kindly let me know. If there is a bigger concept behind it then tell me i'll go read it. Because I searched on google What is "::" in java. and got java operators in result. Help

frigid trailBOT
#

<@&987246399047479336> please have a look, thanks.

unique ember
#

its called a method reference

#

sth introduced in java 8

#

together with lambdas and functional interfaces

#

its explained in this post:

frigid trailBOT
#

You have the following options to create instances of interfaces or abstract classes:

  1. Create a class that extends and use new
  2. Use an anonymous class
    Supposed we have an interface which only offers one method (it's called functional interface then), we additionally have the following two options to create instances of it:
  3. Use a lambda expression
  4. Use a method reference
    As example, we want to create a multiplication instance, using the following interface:
@FunctionalInterface
public interface Operation {
  int op(int a, int b);
}
  1. Create a class that extends and use new:
public class Multiplicator implements Operation {
  @Override
  public int op(int a, int b) {
    return a * b;
  }
}
Operation operation = new Multiplicator();
System.out.println(operation.op(5, 2)); // 10
  1. Use an anonymous class:
Operation operation = new Operation() {
  @Override
  public int op(int a, int b) {
    return a * b;
  }
};
System.out.println(operation.op(5, 2)); // 10
  1. Use a lambda expression:
Operation operation = (a, b) -> a * b;
System.out.println(operation.op(5, 2)); // 10
  1. Use a method reference:
// Somewhere else in our project, in the MathUtil` class
public static int multiply(int a, int b) {
  return a * b;
}
Operation operation = MathUtil::multiply;
System.out.println(operation.op(5, 2)); // 10
unique ember
#

(method 4, but the rest of the post kinda leads up to it, explaining what it is and what it does)

serene fjord
#

Okay.

mental flicker
unique ember
#

sorry, what?

mental flicker
serene fjord
#

Ah. It happens.

umbral sluice