0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

lamda expressionをfunctional interfaceに

Last updated at Posted at 2023-01-11

lamda expressionはmethodそのものを表していて
method reffereceのように扱える

以下はfunctional interfaceのFactoryInterface#get()に対して
外部からlamda expressionを代入して、切り分けすることにより
SampleClassA⇒SampleClassBに変更した際に、businessLogicに影響を与えない

interface FactoryInterface<T>{
    T get();
}
interface SampleInterface{
    void method();
}
class SampleClassA implements SampleInterface {
    public void method() {
        System.out.println("I am SampleClassA method");
    }
}
class SampleClassB implements SampleInterface {
    public void method() {
        System.out.println("I am SampleClassB method");
    }
}
public class Outer {
    public static void main(String[] args) {
        Outer o = new Outer();
        o.businessLogic(() -> {return new SampleClassA();});
    }
    void businessLogic(FactoryInterface<SampleInterface> fi) {
        SampleInterface si = fi.get();
        si.method();
    }
}
I am SampleClassA method

argument, lambda expressionでfunctional interfaceを呼び分ける

public class Outer {
    public static void main(String[] args) {
        method(() -> System.out.println(""));
        method(() -> "");
        method((x) -> {System.out.println("");});    //blockにしないとFunctionも候補、曖昧エラー。理由不明
        method((x) -> "");
    }
    static void method(Runnable r) {
        System.out.println("runnable argument");
    }
    static void method(Supplier<String> s) {
        System.out.println("Supplier argument");
    }
    static void method(Consumer<String> c) {
        System.out.println("Consumer argument");
    }
    static void method(Function<String, String> f) {
        System.out.println("Function argument");
    }
}
runnable argument
Supplier argument
Consumer argument
Function argument
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?