람다 표현식은 바디 바깥에서 선언된 변수에 접근할 수 있다.
Java 람다는 아래 세가지 타입의 변수를 캡쳐 할 수 있다.
- Local variables
- Instance variables
- Static variables
Local Variable Capture
public interface MyFactory { public String create(char[] chars); }
String myString = "Test"; MyFactory myFactory = (chars) -> String.join(":",myString, new String(chars));
지역 변수를 캡쳐링 할때는 두 가지 제약조건이 있다.
- 지역변수는 final로 선언돼있어야한다.
- final로 선언되지 않은 지역변수는 final처럼 동작해야한다.즉, 값의 재할당이 일어나면 안 된다.
Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final
제약 조건에 대한 고찰 링크
Instance Variable Capture
public class EventConsumerImpl { private String name = "MyConsumer"; public void attach(MyEventProducer eventProducer){ eventProducer.listen(e -> { System.out.println(this.name); }); } }
Static Variable Capture
public class EventConsumerImpl { private static String someStaticVar = "Some text"; public void attach(MyEventProducer eventProducer){ eventProducer.listen(e -> { System.out.println(someStaticVar); }); } }