1. 람다식이란?
익명 함수를 간단하게 표현하는 방법. (람다식은 인터페이스의 메서드를 구현하는 코드 블록) 일반적으로 함수를 정의하고 호출하는 과정을 생략하고, 함수의 로직을 간결하게 표현할 수 있음. 다른 함수의 인자로 전달되거나 함수의 반환값으로 사용될 수 있다. 람다식을 사용하면 익명 클래스를 생성하지 않고도 인터페이스의 구현을 간결하게 표현할 수 있다 (= 구현체를 클래스로 별도 선언해서 일일이 적용하는 번거로움을 피할 수 있다.)
인터페이스는 new를 못하기 때문에 클래스를 따로 만들어서 그걸 받아서 대입함 넘 길고, 번거롭고, 쓸데없는 클래스가 늘잖아 ㅠ 그래서 나온게 람다식
주로 함수형 인터페이스를 구현하는 익명 구현체를 간결하게 표현하기 위해 사용된다. 따라서 이벤트 처리를 위한 인터페이스인
ActionListener
, MouseListener
, KeyListener
등과 같은 이벤트 리스너를 구현할 때 주로 람다식을 사용1-2. 람다식 표현방법
- 인자 입력란 ‘()’사이에 입력 - 자료형 생략 - 단문 코드인 경우, 중괄호 생략 - 실질적인 실행 부분만 입력
2. 예시 1
package ex07.example; // 라이브러리 판매자가 생성 interface EventListener { //인터페이스 void action(); } // 라이브러리 판매자가 생성 // click을 실행하는게 목적 class MyApp { public void click(EventListener l) { // l = 인터페이스를 구현받는 class 객체 //(EventListener l) = 인터페이스를 new한 클래스를 매개변수로 받는 것과 비슷하다. (인터페이스는 new안되긴한데 이해만 이렇게) l.action(); //동적바인딩 } } //저걸 보고 우리가 써야하는 것 public class InterEx02 { public static void main(String[] args) { MyApp app = new MyApp(); app.click(() -> { //람다식 //인터페이스의 구현체 System.out.println("회원가입 로직이 시작됩니다."); }); } }
(EventListener l) 의 l = 인터페이스를 구현 받는 class 객체 = 람다식. 을 매개변수로 받음
* MyApp 클래스의 click 메서드가 EventListener 인터페이스를 매개변수로 받기 때문에
람다식 사용!
* EventListener은 단 하나의 추상 메서드 action만을 가지고 있는 함수형 인터페이스
* 인터페이스는 new할 수 없으니까, new 할 수 있는 애한테 기생해서(?) new 된다.
* l은 click 메서드의 매개변수로 람다 표현식을 받음


2-2. 람다식을 사용하지 않았다면 원래 코드

즉,
app.click(() -> {
는 Acl이라는 class 객체를 click 메소드의 매개변수로 받은 것.3. 예시 2
ctrl + 좌클릭으로 라이브러리에서 EventListener가 어디 타입인지 확인 > ActionListener 타입 확인!

"ㄹㅇㄴ마ㅓㅣㅓㄹㅇ남"을 출력하고 싶어서 ActionListener() 타입을 넣으려니까 오류가 발생

임의로 U라는 클래스를 만든다. ActionListener을 인터페이스하니까, 클래스 U는 ActionListener와 같은 타입이다! (heap에 같이 붙어서 뜬다. 동적 바인딩!)

하지만 U도 new 할 수 없음. 애가.. 익명 클래스 그거인듯? < 확인 하기

U 클래스의 필요 없는 부분들을 하나씩 지워나감 아래의 코드를 ' btn1.addActionListener( ' 에 붙여넣기.

람다식을 활용한 모습. (ctrl + space)

ActionEvent 타입명을 넣어도 오류는 안나지만, 지워서 써라.

이렇게 지워서 써라!! > 람다식 완성~!
완성된 코드
package ex07.example; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MyFrameEx01 { static int num = 1; public static void main(String[] args) { JFrame jf = new JFrame(); //jf.setLayout(new BorderLayout()); jf.setSize(300,500); JButton btn1 = new JButton("더하기"); JButton btn2 = new JButton("빼기"); JLabel la1 = new JLabel(num+""); //label에는 String만 넣을 수 있다. jf.add("North", btn1); jf.add("South", btn2); jf.add("Center", la1); btn1.addActionListener((e) -> { System.out.println("ㄹㅇㄴ마ㅓㅣㅓㄹㅇ남"); }); btn2.addActionListener(e -> { num--; if (num < 0) { num = 0; } la1.setText(num + ""); }); //jf.add(btn1); // (=jf.add(new JButton("클릭"));) jf.setVisible(true); } }
람다식 심화
https://inblog.ai/nomads?traffic_type=internal 님 블로그 참조
함수형 인터페이스에서 보고 왔어요? (바로가기)



중괄호가 없으면 리턴을 안적어도 됨
람다 표현식의 결과가 자동으로 반환 되기 때문!
중괄호가 있는 경우에는 명시적으로 return 키워드를 사용하여 값을 반환
다만!! 람다식의 몸체가 단일 표현식인 경우에는 { }와 return 키워드를 생략할 수 있다.
[ 단일 표현식 ]
코드가 한 줄로 표현 + 결과값이 반환된다 = { } 생략 가능
(if문처럼 코드를 한 줄로 쓰면 생략 가능 < 생각하면 될 듯?)

'단일 표현식'이라 { } 와 return을 생략한 모습
익명 클래스 (익명 클래스 대체로 람다식 사용)

Share article