A functional interface is an interface in which only one abstract method is declared. Other than that, there are no particular restrictions. For example, it doesn't matter if you have multiple default methods or private methods.
A function that gives an interface implementation on the client (caller). By using a lambda expression, you don't have to create a concrete class that implements the interface. Lambda expressions are only possible if you give an implementation of a functional interface. This is because when there are multiple abstract methods in the interface to which you want to give an implementation, the compiler cannot specify which abstract method to give the implementation (definition) to.
When giving an implementation using a lambda expression, local class, or anonymous class in a method, a function that allows the client's local variables to be used in the block that gives the implementation. Variables used as closures are copied as fields in lambda instances (for java). In some languages references are passed. Variables passed in closures are final.
InfintieIntSequence.java
public interface InfiniteIntSequence{
default public boolean hasNext(){ return true; }
public int next();
public static InfiniteIntSequence generate(IntSupplier s){
return s::getAsInt; //@1
}
public static InfiniteIntSequence iterate(int seed, IntUnaryOperator f){
return new InfiniteIntSequence(){
int lseed = seed; //@2
@Override public int next(){
int res=lseed;
lseed=f.applyAsInt(lseed);
return res;
}
};
}
public static InfiniteIntSequence random(int from, int until){
Random r = new Random();
int bound = until-from;
if(0<bound) return ()->r.nextInt(bound)+from;
else throw new IllegalArgumentException();
}
public static InfiniteIntSequence range(int from){
return iterate(from, i -> i+1 );
}
default public void forEach(IntConsumer c, int n){
while(n-- > 0 && hasNext() ) c.accept(next());
}
}
What is returned by @ 1: return is an instance of class that inherits the InfiniteIntSequence interface, overriding the next () method. Since InfiniteIntSequence is a functional interface, it is guaranteed that there is only one abstract and sod. Therefore, the compiler can understand that overriding next (), so you can omit writing various things. next () is a signature method that returns an int with no arguments.
Recommended Posts