Java

람다 (Lambda)

일태우 2020. 2. 18. 23:04
반응형

람다

람다 표현식이란 클로져(Closures)나 익명 함수, 익명 메서드(anonymous methods, anonymous functions)로 알려져있다. 다시 말해 자바에서는 익명 메서드를 나타내기 위한 표현식(expression)이라 생각하면 된다.

(int x, int y) -> x + y

() -> 42

(String s) -> { System.out.println(s); }

첫번째 식은 매개변수로 x, y를 받고 x, y의 합을 반환한다

두번째는 integer 42를 반환한다.

마지막은 매개변수로 String s를 받고 그것을 콘솔에 출력, 아무것도 반환하지 않는다.

 

일반적인 문법은 매개변수들, ->(화살표) 그리고 body로 이루어진다. body는 단독으로 표현 하거나 { } 중괄호 블럭으로 구현 할 수 있다.

단득으로 표현하는 경우의 body는 단순하게 계산되고 반환된다. { } 블럭의 경우는 메서드와 같이 동작하고 return의 경우 익명 함수의 호출자에게 반환한다.

public interface ExampleInterface {
	public String callMe();
}

public interface ExampleInterface2 {
	public int sum(int a, int b);
}

public class ExampleClass {
	public static void main(String[] args) {
		
		//기본적인 익명 메서드 작성법
		ExampleInterface ex = new ExampleInterface() {
			@Override
			public String callMe() {
				return "Hello!";
			}
		};
		
		System.out.println(ex.callMe());
		
		//람다 표현식
		ExampleInterface ex2 = () -> {
			return "Hello2!";
		};
		
		System.out.println(ex2.callMe());
		
		//람다 표현식2
		ExampleInterface ex3 = () -> "hello3";
		System.out.println(ex3.callMe());
		
		//람다 표현식3
		ExampleInterface2 sumEx = (int a, int b) -> a + b;
		System.out.println(sumEx.sum(1, 2));
	}
}
  • 기본적으로 람다 인터페이스(Functional Interface 라고한다.) 에는 추상메서드가 1개여야 한다.
  • 매개변수를 생략할 수 있다.(대부분의 경우)
  • return을 생략할 수 있다.
  • {}도 생략 할 수 있다.

Functional Interface

  • 함수형 인터페이스는 추상메서드가 1개 여야 한다. 단 default와 static 메서드는 제약이 없다.
  • @FunctionalInterface 어노테이션을 지원한다. 함수형 인터페이스임을 명시하고 유효성 검증이 가능하다.
  • Object로 형변환이 불가능하며 함수형 인터페이스끼리만 형변환이 된다.

http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html

 

State of the Lambda

State of the Lambda September 2013 Java SE 8 Edition This is an informal overview of the enhancements to the Java programming language specified by JSR 335 and imple

cr.openjdk.java.net

 

반응형