HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
WhiteShip-LiveStudy
WhiteShip-LiveStudy
/
15주차 과제: Lambda Expressions
15주차 과제: Lambda Expressions
/
Variable Capture and Effectively final
Variable Capture and Effectively final
Variable Capture and Effectively final

Variable Capture and Effectively final

 
람다 표현식은 바디 바깥에서 선언된 변수에 접근할 수 있다.
 
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));
 
지역 변수를 캡쳐링 할때는 두 가지 제약조건이 있다.
  1. 지역변수는 final 로 선언돼있어야한다.
  1. 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); }); } }