티스토리 뷰

● @FunctionalInterface란?

- @FunctionalInterface Annotation이 붙으면 해당 interface가 단 하나의 abstract method(추상 메소드)만 가지는 interface라는 것을 의미한다.

- 다른 말로 Single Abstract Method interface 라고도 한다.

- Function interface의 실제 구조는 아래와 같다.(실제로 Function interface를 들어가서 내용을 복붙한 것이다.)

package java.util.function;

import java.util.Objects;

@FunctionalInterface
public interface Function<T, R> {

    R apply(T t);

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

- Default method와 static method는 이미 구현이 되어있으므로 추상메소드가 아니다.

- 따라서 @FunctionalInterface Annotation이 붙으면 단 하나의 abstract method(추상 메소드)만 가진다는 사실에 영향을 미치지 않는다.

- Default method와 static method는 몇 개가 있든 상관없다.

- 위 코드에서 단 하나의 abstract method(추상 메소드)는 apply method 이다.

- 현이 되지 않은 method가 하나만 있으면 FunctionalInterface 라고 할 수 있다.

- java.lang.Runnable, java.util.Comparator, java.util.concurrent.Callable 등도 @FunctionalInterface 이다.

 

 

input을 3개 받는 interface 만들기

- @FunctionalInterface Annotation을 이용해 새로운 interface를 만들어보자

 

1. TriFunction interface 만들기

package com.fastcampus.functionalprogramming.chapter3.util;

// input이 3개인 interface를 만들어보자 
@FunctionalInterface
public interface TriFunction<T, U, V, R> {
	// @FunctionalInterface가 붙었기에 단 하나의 abstract method를 가져야한다.
	R apply(T t, U u, V v);
	// method 이름이 반드시 apply 일 필요는 없다.
	// Function interface, BiFunction interface 와의 통일성을 위해 apply라고 지은 것일 뿐이다.
}

 

2. Lambda를 이용해 TriFunction interface 구현

package com.fastcampus.functionalprogramming.chapter3;

import com.fastcampus.functionalprogramming.chapter3.util.TriFunction;

public class Chapter3Section4 {
	public static void main(String[] args) {
		// TriFunction interface를 Lambda를 이용해 구현해보자
		TriFunction<Integer, Integer, Integer, Integer> addThree = (Integer x, Integer y, Integer z) -> {
			return x + y + z;
		};
		int result = addThree.apply(10, 10, 10);
		System.out.println("result : " + result);
		
		// 조금 더 간단하게
		TriFunction<Integer, Integer, Integer, Integer> addThree2 = (x, y, z) -> x + y + z + 77;
		int result2 = addThree2.apply(10, 10, 10);
		System.out.println("result2 : " + result2);
	}
}

TriFunction interface
TriFunction interface 구현

 

 

추상메소드, 추상클래스 관련하여 읽을만한 글

https://www.tcpschool.com/java/java_polymorphism_abstract

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함