클래스의 멤버 사용

람다식 실행 블록에는 클래스의 멤버인 필드와 메소드를 제약없이 사용할 수 있다.

람다식 실행 블록내에서 this는 람다식을 실행한 객체의 참조이다.


Exam    ( UsingThis 의 Filed2 와 Inner의 Filed2이름이 같을때 this 

public class UsingThis {
public int outterField1 = 10;
public int Filed2 = 1000;

class Inner {
int innerField1 = 20;
int Field2 = 2000;

void method() {
MyFunctionalInterface fi = () -> {
System.out.println("outterField = " + outterField1); //결과값 10
System.out.println("innerField = " + innerField1); //결과값 20

System.out.println("Field2 = " + Field2); // 결과값 2000
System.out.println("Field2 = " + Field2); // 결과값 2000

System.out.println("UsingThis.this.Filed2 = " + UsingThis.this.Filed2); //결과값 1000
System.out.println("this.Field2 = " + this.Field2); // 또는 Field2 호출 결과값 2000
};
fi.method();
}
}
}



로컬 변수의 사용

람다식은 함수적 인터페이스의  익명 구현 객체를 생성한다.

람다식에서 사용하는 외부 로컬 변수는 final 특성을 갖는다.

Exam


public class UsingLocalVariable {
void method(int arg) {
int localVar = 40;

// arg = 31; 수정하려고하면 에러 발생 아래 람다식에서 사용했기때문에 final
// localVar = 20; 수정하려고하면 에러 발생 아래 람다식에서 사용했기때문에 final

MyFunctionalInterface fi = () -> {
System.out.println("arg = " + arg); //arg 는 final특성을 가짐
System.out.println("localVar = " + localVar); //localVar 는 final특성을 가짐
};
fi.method();
}
}



'JAVA > JAVA' 카테고리의 다른 글

자바 컬렉션) Set 컬렉션  (0) 2018.06.14
람다식) 표준 API의 함수적 인터페이스  (0) 2018.06.10
람다식 타겟 타입과 함수적 인터페이스  (0) 2018.06.09
람다식 기본 문법  (0) 2018.06.09
람다식이란?  (0) 2018.06.09

타겟 타입(target type)

람다식이 대입되는 인터페이스를 말한다.                                    인터페이스(타겟 타입) 변수 = 람다식;

익명 구현 객체를 만들 때 사용할 인터페이스이다.


함수적 인터페이스(functional interface)

모든 인터페이스는 람다식의 타겟 타입이 될 수 없다.

람다식은 하나의 메소드를 정의하기 떄문에..

나의 추상 메소드만 선언된 인터페이스만 타겟 타입이 될 수 있다.


함수적 인터페이스

하나의 추상 메소드만 선언된 인터페이스를 말한다.


@FunctionalInterface  어노테이션

하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함

두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생


매개 변수와 리턴값이 없는 람다식

@FunctionalInterface

public interface MyFunctionalInteface (

              public void method();

}

            MyFunctionalInterface fi = () -> { ... }

            fi.method(); 



Exam

                      //하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함
@FunctionalInterface // 두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생
public interface MyFunctionalInterface {
public void method();
// public void method2(); 주석을 해제하면 컴파일 오류 발생
}



public class MyFunctionalInterfaceExample {
public static void main(String[] args) {

MyFunctionalInterface fi;

fi = () -> {
String str = "method call1";
System.out.println(str);
};
fi.method(); //실행결과 method call1

fi = () -> { System.out.println("method call2");};
fi.method(); //실행결과 method call2

fi = () -> System.out.println("method call3"); //실행문이 하나 이므로 중괄호 생략
fi.method(); //실행결과 method call3

fi = new MyFunctionalInterface() {
@Override
public void method() {
System.out.println("method call4");
}
};
fi.method(); //실행결과 method call4
}
}


매개변수가 있는 람다식

@FunctionalInterFace

public interface MyFunctionalInterface {

       public void method(int x);

      MyFunctionalInterface fi = (x) -> { ... }  또는  x -> { ... }

      fi.method(5) 


Exam

                      //하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함
@FunctionalInterface // 두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생
public interface MyFunctionalInterface {
public void method(int x); //매개변
// public void method2(); 주석을 해제하면 컴파일 오류 발생
}


public class MyFunctionalInterfaceExample {
public static void main(String[] args) {

MyFunctionalInterface fi;

fi = (x) -> {
int result = x * 5;
System.out.println(result);
};
fi.method(2); //실행 결과 10


fi = (x) -> System.out.println(x * 5); //실행문이 하나일 경우 중괄호 생략 {}
fi.method(2); //실행 결과 10

fi = x -> System.out.println(x * 5); //매개변후가 하나일 경우 괄호() 생략
fi.method(2); //실행 결과 10
}
}


리턴값이 있는 람다식

@FunctionalInterFace

public interface MyFunctionalInterface {

       public int void method(int x, int y);

 MyFunctionalInterFace fi = (x, y) -> { ...; return 값; }

 int result = fi.method(2, 5)




 MyFunctionalInterface fi = (x, y) ->{

      return x + y;

 MyFunctionalInterFace fi = (x, y) -> x + y;

  MyFunctionalInterFace fi = (x, y) -> {

     return sum(x, y);

}

 MyFunctionalInterFace fi = (x, y) -> sum(x, y); 


Exam

                      //하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함
@FunctionalInterface // 두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생
public interface MyFunctionalInterface {
public int method(int x, int y); //매개변수가 2개 int타입 리턴
// public void method2(); 주석을 해제하면 컴파일 오류 발생
}


public class MyFunctionalInterfaceExample {
public static void main(String[] args) {

MyFunctionalInterface fi;

fi = (x, y) -> {
int result = x + y;
return result;
};
System.out.println(fi.method(2,5)); //실행 결과 7

fi = (x, y) -> { return x + y; };
System.out.println(fi.method(2,5)); //실행 결과 7

fi = (x, y) -> x + y; //중괄호 블럭에 return문만 있을경우 중괄호 생략가능, return 생략가능
System.out.println(fi.method(2,5)); //실행 결과 7


//아래의 static int sum() 으로 실행
fi = (x, y) -> sum(x, y); // == {return sum(x, y);};
System.out.println(fi.method(2,5)); //실행 결과 7

}
public static int sum(int x, int y) {
return (x + y);
}
}


함수적 스타일의 람다식을 작성하는 방법


(타입 매개변수, ...) -> { 실행문; ...}           |             (int a) -> { System.out.println(a); }


매개 타입은 런타임시에 대입 값에 따라 자동으로 인식하기 때문에 생략 가능

(a)   ->   { System.out.println(a) };


하나의 매개변수만 있을 경우에는 괄호() 생략 가능

              a   ->  { System.out.println(a); }


하나의 실행문만 있다면 중괄호 {} 생략 가능

    a -> System.out.println(a)


매개변수가 없다면 괄호 ()를 생략할 수 없음

         () -> { 실행문; ... }


리턴값이 있는 경우, return 문을 사용

(x ,y) -> { return x + y };


중괄호 {}에 return 문만 있을 경우, 중괄호를 생략 가능

      (x, y) -> x + y 




+ Recent posts