Skip to content

람다 문법, lambda에서의 생략 #8

Open
@sendkite

Description

@sendkite

주제

람다 문법, lambda 바디에 {}는 어떤 기준일까

선정 배경

{} 가 있고 없고의 기준이 명확하게 나와있지 않다.

본론

  • 람다 바디가 한줄이면 {} 를 생략할 수 있다.
String hello = () -> return "hello"; 
  • 한줄이면 return 또한 생략할 수 있다.
String hello = () -> "hello"; 
  • 매개변수 타입은 생략할 수 있다. (앞에 제네릭으로 추론)
BinaryOperator<Integer> sum = (a, b) -> a + b;  // Integer a, Integer b에 타입 생략
  • 변수 캡처 기능
  • 익명 클래스, 로컬 클래스는 내부 scope을 가져서 상태 변경 가능
  • 그러나 람다는 method와 scope이 같다. 컴파일 에러를 뱉는다.
public class Foo {
    
    public static void main() {
        Foo foo = new Foo();
        foo.fun()
    
        private void run() {
            int baseNumber = 10; // 참조하는 상태 값. 앞에 final이 생략. (effective final)
            IntConsumer printInt = (i) -> {
                System.out.println(i + baseNumber);
            }
           
            printInt.accept(10);
        }
    } 
} 

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions