This article is an upgrade article for the vulnerable lambda. We will compare the "anonymous class" that can be used up to SE7 with the SE8 function "lambda expression".
After all, lambda expressions are sometimes called "anonymous functions" or "anonymous functions" and are a concept very similar to anonymous classes. [^ 1]
[^ 1]: Strictly speaking, "lambda function" and "anonymous function" are equal, and lambda expression is a notation of lambda function.
Roughly speaking, the difference between an anonymous class and a lambda expression (anonymous function) is "class or method". Understanding that an anonymous class is defined as an anonymous class and an anonymous method is defined as a lambda expression (anonymous function). I think that there is almost no problem.
Suppose you have an interface that has a method for primality testing.
Primes.java
public interface Primes {
boolean isPrime(Integer param);
}
Normally, implements are like this.
PrimesImpl.java
public class PrimesImpl implements Primes {
@Override
public boolean isPrime(Integer param) {
for (int i = 2; i < param; i++) {
if (param % i == 0) {
return false;
}
}
return true;
}
}
Here's how to call it. New.
Main.java
public class Main {
public static void main(String[] args) {
System.out.println(new PrimesImpl().isPrime(7));
}
}
Using an anonymous class:
Main.java
public class Main {
public static void main(String[] args) {
Primes primesInner = new Primes() {
@Override public boolean isPrime(Integer param) {
for (int i = 2; i < param; i++) {
if (param % i == 0) {
return false;
}
}
return true;
}
};
System.out.println(primesInner.isPrime(7));
}
}
Main class ONLY because it is implemented while newing the class inside.
Using a lambda expression:
Main.java
public class Main {
public static void main(String[] args) {
Primes primesLambda = param -> {
for (int i = 2; i < param; i++) {
if (param % i == 0) {
return false;
}
}
return true;
};
System.out.println(primesLambda.isPrime(7));
}
}
It is a little omitted from the anonymous class.
The method name also disappears. This is because the Primes interface meets the requirements of the function interface. The method is self-explanatory because "function interface = always one method to implement".
By the way, if Primes is not a function interface (if there is not one method to implement), lambda expression cannot implement multiple methods and compile error.
Type inference works hard for arguments and return values.
Lambda Lambda like this.
Main.java
public class Main {
public static void main(String[] args) {
Primes primesFunction = param -> IntStream.range(2, param).noneMatch(i -> (param % i) == 0);
System.out.println(primesFunction.isPrime(7));
}
}
Don't write because you can't maintain it! The one who gets angry.
that's all Please let me know if you make a mistake! !! !!
Kishida Hatena Java8 Lambda grammar extension summary
Recommended Posts