Collective Intelligence

Java 8 Lambda(람다) 식 본문

개발/JAVA

Java 8 Lambda(람다) 식

유경파 2016. 6. 10. 17:39

작년에 새로운 프로젝트에 들어가면서 자바 8이 나왔길래 무작정 설치를 하고 적용했다.


그러다가 문득 그래도 버전 앞자리가 바뀐건데 다른게 있겠지 하고 둘러보다가 Lambda 표현식을 사용할 수 있다고 한다.


매뉴얼이나 튜토리얼을 찾아보니 람다식을 설명하면서 Anonymous Classes, 혹은 Anonymous Inner Classes를 주로 예를 드는데


람다식을 쓰면 Anonymous Classes를 Compact하게 구현해서 가독성도 뛰어나고 깔끔하다는 식으로 설명을 해두었다.



위에서 보듯이 5줄을 코딩해야 하는 (이클립스에선 자동완성이지만) 5줄을 1줄로 끝낼 수 있다고 한다.


표현식이 좀 낯설기는 하지만 소스가 많이 줄어든다는 것은 디버깅도, 운영도 편하기에 아주 괜찮은 것 같다.


이 방법 외에도 method가 하나인 interface에도 사용할 수 있다고 한다.



이쯤되면 대충 어떻게 쓰일 수 있는지 알 수 있다. 숙달이 되면 뭐 코딩도 빨라질 것 같기도 하고, 소스 이해도 빠를 것 같다.


그럼 끝으로 람다식의 구조는 다음과 같다. 기본 구조는 (argument) -> (body)로 되어있다.


예를 들면

(int a, int b) -> { return a + b;}  //int는 생략해도 된다.

() -> System.out.println("Hello"); //argument가 없고, Hello가 출력된다.

(String s) -> { System.out.println(s);} //String s 가 정의되지 않아서 null이 출력된다.

 


아래는 자세한 설명이다.


  • A lambda expression can have zero, one or more parameters.
  • The type of the parameters can be explicitly declared or it can be inferred from the context. e.g. (int a) is same as just (a)
  • Parameters are enclosed in parentheses and separated by commas. e.g. (a, b) or (int a, int b) or (String a, int b, float c)
  • Empty parentheses are used to represent an empty set of parameters. e.g. () -> 42
  • When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. a -> return a*a
  • The body of the lambda expressions can contain zero, one or more statements.
  • If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.
  • When there is more than one statement in body than these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.