Generic - Invariance, Covariance, Contravariance
Spring batch를 쓰다보면 ItemWriter에 void write(List<? extends T> var1) 이런 메서드가 있어 왜 저런 제네릭 타입을 쓰는걸까 궁금했었는데 이제서야 찾아보게 되었다. contravariance 개념에 대한 글들을 봐도 뭔가 직관적이지 않아서 이해하는데에만 몇 시간이나 걸렸는데, 이해하고 나니 어찌보면 단순하다. 최대한 정리해봤다. Generic 용어 처음엔 일단 뭐라고 검색해야할지 명칭조차 까먹어서 다시 정리를 해봤다. 이펙티브 자바에 나오는 용어 기준이다. ? : wildcard. unknown type을 나타낸다 List<?>: unbounded wildcard type(비한정적 와일드카드 타입) List<? extends Integer>, List<? super Integer> : bounded wildcard type(한정적 와일드카드 타입) ? super Integer : Integer이거나 Integer의 supertype이란 뜻 ? extends Integer : Integer이거나 Integer의 subtype이란 뜻 E : formal type parameter(정규타입 매개변수) List<E> : generic type Invariance, Covariance, Contravariance type과 subtype간의 관계 각각 불공변, 공변성, 반공변성으로 번역할 수 있는데…차라리 영어가 더 쉽다 in- 은 not, co- 는 함께, contra- 는 반대의 covariant: A가 B의 subtype이면 f(A)도 f(B)의 subtype contravariant: A가 B의 subtype이면 f(B)가 f(A)의 subtype invariant: 위에꺼 둘다 안됨 Invariance 1 2 3 4 5 6 interface Animal { void eat() } class Panda extends Animal { void eat() } Panda는 Animal의 하위 타입이지만, List<Panda>는 List<Animal>의 하위타입이 아니다. ...