Loading...

JAVA / / 2022. 2. 3. 10:55

자바 40강. 화살표 함수(람다식)

반응형

결국 스레드는 run 메서드(타겟)를 넘기는 게 목적이다

 

Thread t1 = new Thread(() -> {
            
});

( ) -> { }

이 화살표를 화살표 함수(arrow function)라고 한다.

 

어차피 스레드 타겟 자리에는 Runnable 타입만 들어올 수 있기 때문에

화살표 함수가 들어오면 중괄호 내부를 run 메서드라고 인식하게 된다.

 

OS가 알고 있는 메서드는 하나밖에 없기 때문이다.

 

이 화살표 함수는 메서드만 넘기기 위한 방법이다.

 

실제로는 익명 클래스가 넘어가는 것이다.

 

중괄호 내부는 run메서드이다.

괄호 부분은 run메서드의 매개 변수 자리이다.

 

계속 new 하기 불편해서 나온 문법이다.

package site.metacoding.ex23;

interface Remocon {
    public abstract void on(int i);
}

class Samsung {
    public void 수리를위한테스트(Remocon r) {
        r.on();
    }
}

public class ArrowEx01 {
    public static void main(String[] args) {
        Samsung s = new Samsung();

        s.수리를위한테스트((int i)-> {

        });
    }
}

 

 

화살표 함수를 사용하지 못하는 경우도 있다.

인터페이스가 두 개의 추상 메서드를 가지고 있을 때는

화살표가 가리키는 메서드가 무엇인지 모르기 때문에 사용할 수 없다.

package site.metacoding.ex23;

interface Remocon {
    public abstract void on(int i);
    public abstract void off(int i);
}

class Samsung {
    public void 수리를위한테스트(Remocon r) {
        r.off();
    }
}

public class ArrowEx01 {
    public static void main(String[] args) {
        Samsung s = new Samsung();

        s.수리를위한테스트(new Remocon() {

            @Override
            public void on(int i) {
                // TODO Auto-generated method stub
            }
            
            @Override
            public void off(int i) {
                // TODO Auto-generated method stub
            }  
        });
    }
}

즉 메서드가 2개 이상일 때는 화살표 함수를 사용할 수 없고

2개 이상의 메서드를 직접 구현해주어야 한다.

 

 

 

 

 


[출처]

https://cafe.naver.com/metacoding

 

메타코딩 : 네이버 카페

코린이들의 궁금증

cafe.naver.com


메타 코딩 유튜브
https://www.youtube.com/c/%EB%A9%94%ED%83%80%EC%BD%94%EB%94%A9

 

메타코딩

문의사항 : getinthere@naver.com 인스타그램 : https://www.instagram.com/meta4pm 깃헙 : https://github.com/codingspecialist 유료강좌 : https://www.easyupclass.com

www.youtube.com

 
반응형