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
#Scope Resolution operator(::) in java?
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
its called a method reference
sth introduced in java 8
together with lambdas and functional interfaces
its explained in this post:
You have the following options to create instances of interfaces or abstract classes:
- Create a class that
extendsand usenew - Use an
anonymousclass
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: - Use a
lambdaexpression - 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);
}
- Create a class that
extendsand usenew:
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
- Use an
anonymousclass:
Operation operation = new Operation() {
@Override
public int op(int a, int b) {
return a * b;
}
};
System.out.println(operation.op(5, 2)); // 10
- Use a
lambdaexpression:
Operation operation = (a, b) -> a * b;
System.out.println(operation.op(5, 2)); // 10
- 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
zabuzard • used /tag id: instance
·
(method 4, but the rest of the post kinda leads up to it, explaining what it is and what it does)
Okay.
The exemple style are all over the place.
sorry, what?
My bad, just my phone,
Ah. It happens.
Book teaching how to write modern and effective Java.