7,540
edits
Changes
→Konstruktor referenciát használunk
===Konstruktor referenciát használunk===
Emlékezzünk rá, hogy funkcionális IF definíciókat meg kelhet adni azon osztály konstruktor referenciájával is, amikkel a funkcionális metódus visszatér, abban az esetben ha ez az osztály rendelkezik olyan konstruktorral, aminek a paraméterei megegyeznek a funkcionális metódus paramétereivel.
Pl. ha adott a már ismert Funkcionális if:
<source lang="java">
@FunctionalInterface
public interface MyFunction {
MyString process(String input);
}
</sring>
Akkor a funkcionális if definiálható a '''MyString::new''' konstruktor referenciával, ha rendelkezik String paraméterű konstruktorral:
<source lang="java">
public class MyString {
private String input;
public MyString(String input) { <<<<---------- ez itt a lényeg!!!!
System.out.println("MyString consturctor is called with input:" + input);
this.input = input;
}
public String getInput() {
return input;
}
}
</source>
<br>
Nézzük a már ismert java ENUM-ot, ezt egészítsük ki egy új értékkel: '''ENUMV2''', ahol a funkcionális if-et a konstruktorban a 'MyString' konstruktor referenciájával adjuk meg:
<source lang="java">
public enum MyEnum2 {
ENUMV1(var1 -> {
System.out.println("ENUM lambda is called with input: " + var1);
return new MyString(var1);
}),
ENUMV2(MyString::new) <<<-------------- ez itt a lényeg!!!
;
private final MyFunction function;
private MyEnum2(MyFunction function) {
System.out.println("ENUM constructor is called with input");
this.function = function;
}
public MyFunction getFunction() {
return function;
}
}
</source>
Ha példányosítjuk az enum-ot a ENUMV2 értékkel, majd azon meghívjuk a funkcionális if process(..) metódusát, akkor fog lefutni a MyString konstruktora:
<source lang="java">
System.out.println("START");
MyEnum2 myEnum22 = MyEnum2.ENUMV2;
System.out.println("Enum was created");
myEnum22.getFunction().process("prcoess again");
</source>
<br>
Az output az alábbi lesz:
<pre>
START
Enum was created
MyString consturctor is called with input:prcoess again
</pre>
<br>
<br>
==Mire használható (komplex példa)==