TIL

아이템 22 일반적인 알고리즘을 구현할 때 제네릭을 사용하라

// stdlib에 있는 대표적인 제네릭 함수인 filter
inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
 val destination = ArrayList<T>
 for (element in this) {
	 if (predicate(element)) {
		 destination.add(element)
	 }
 }
 return destination
}

제네릭 제한

// 특정 타입의 스브타입만 허용
fun <T : Comparable<T>> Iterable<T>.sorted(): List<T> {
	/*...*/
}
inline fun <T, R : Any> Iterable<T>.mapNotNull(transform: (T) -> R?): List<R> {
	return mapNotNullTo(ArrayList<R>(), transform)
}
fun <T : Animal> pet(animal: T) where T: GoodTempered {
	/*...*/
}

// 또는

fun <T> pet(animal: T) where T: Animal, T: GoodTempered {
	/*...*/
}