상세 컨텐츠

본문 제목

[Lambda] 람다 기본 문법

Java

by kwanghyup 2020. 6. 19. 00:30

본문

예제에서 사용할 함수형 인터페이스 

@FunctionalInterface
public interface VoidTypeNoParam {
    void run();
}
@FunctionalInterface
public interface IntTypeOneParam {
    int intOneParam (int value);
}

1. 람다 표현식

public class LamdaExam01 {

    public static void main(String[] args) {

        //익명 객체
        VoidTypeNoParam anonymous = new VoidTypeNoParam() {
            @Override
            public void run() {
                System.out.println("Hello 익명! ");
            }
        };
        anonymous.run();

        // 람다식
        VoidTypeNoParam lambda = () -> {
            System.out.println("Hello 람다 !");
        };
        lambda.run();

        //  한 문장인 경우 중괄호 { }을 생략할 수 있다.
        VoidTypeNoParam lambda2 = () -> System.out.println("중괄호 생략 !");
        lambda2.run();

        /*람다식의 타입은함수형 인터페이스와 일치하지 않는다.
        따라서 형변환이 필요하고 이 형변환은 생략할 수 있다.*/
        VoidTypeNoParam lambda3 = (VoidTypeNoParam) ()->System.out.println("형변환 생략 가능");
        lambda3.run();

        /* 람다식은 Object 타입으로 직접 형변환할 수 없다.
          함수형 인터페이스로 변환 후 오브젝트타입으로 변환 가능하다. */
        // Object obj  =  ()-> System.out.println("되나?");
        Object obj1 = (Object) (VoidTypeNoParam) ()-> System.out.println("오브젝트타입으로 변환");
        Object obj2 = (VoidTypeNoParam) ()-> System.out.println("형변환 생략 가능함");
        System.out.println(obj1);
        System.out.println(obj2);

    }

}

 

public class LamdaExam02 {

    public static void main(String[] args) {

        // 익명 객체
        IntTypeOneParam intTypeOneParam = new IntTypeOneParam() {
            @Override
            public int intOneParam(int value) {
                return (int)(Math.random()*10) + value;
            }
        };
        int anony = intTypeOneParam.intOneParam(4);
        System.out.println(anony);

        /* 람다식 */

        // return을 명시하는 경우 한 문장이어도  중괄호를 생략할 수 없다.
        IntTypeOneParam lamda1 = (int value) -> {return (int)(Math.random()*10) + value; };
        int r1 = lamda1.intOneParam(10);
        System.out.println(r1);

        // retun을 생략할 수 있다. 이 경우 반드시 { } 생략해야함
        IntTypeOneParam lamda2 = (int value) -> (int)(Math.random()*10) + value;
        int r2 = lamda2.intOneParam(10);
        System.out.println(r2);

        // 매개변수의 타입을 추론할 수 있는 경우 이를  생략할 수 있다.
        IntTypeOneParam lamda3 = (value) -> (int)(Math.random()*10) + value;
        int r3 = lamda3.intOneParam(10);
        System.out.println(r3);

        // 매개변수가 하나인 경우 ( )를 생략할 수 있다 .
        IntTypeOneParam lamda4 = value -> (int)(Math.random()*10) + value;
        int r4 = lamda4.intOneParam(10);
        System.out.println(r4);

    }
}

 

2. 내부 클래스에서 람다식의 외부클래스 변수 참조 

/* 내부클래스에서 람다식의 외부클래스변수 참조 */

public class Outer {
    int value = 100;

    public Outer(){
        value = 999; //람다식에서 참조하더라도 생성자에서 값 변경 가능
    }

    class Inner{
            int value = 10;
            Inner(){ value = 99;} // 생성자에서 값 변경 가능

            void innermethod(int i){ // 람다식 내에서 참조하고 있다. final int i 로 간주
                int value = 1; // 람다식 내에서 참조하고 있다. final int value 로 간주
                // value = 9; 에러
                // i = 9999999; 에러

                VoidTypeNoParam voidTypeNoParam = ()->{
                    System.out.println("매서드의 파라미터 i : " + i);
                    System.out.println("람다식이 존재하는 메서드 내 value : " + value);
                    System.out.println("내부 클래스 this.value : "+this.value);
                    System.out.println("외부 클래스 Outer.this.value : " + Outer.this.value);
                };
                voidTypeNoParam.run(); //람다식 실행
            }
    }

}
public class LamdaExam03 {
    public static void
    main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.innermethod(10000);
    }
}

관련글 더보기

댓글 영역