Kotlin 컴파일러는 타입 추론과 마찬가지로 제네릭 타입 인자도 추론할 수 있다.
제네릭 메서드, 제네릭 확장 함수, 제네릭 최상위 함수
제네릭 확장 프로퍼티
제네릭 프로퍼티는 불가능
제네릭 클래스, 제네릭 인터페이스
fun <T: Comparable<T>> max(first: T, second: T): T {
return if (first > second) first else second
}
fun main(args: Array<String>) {
println(max("kotlin", "java"))
}
where
where
fun <T> ensureTrailingPeriod(seq: T)
where T : CharSequence, T : Appendable {
if (!seq.endsWith('.')) {
seq.append('.')
}
}
fun main(args: Array<String>) {
val helloWorld = StringBuilder("Hello World")
ensureTrailingPeriod(helloWorld)
println(helloWorld)
}
<T: Any>
fun <T> process(value: T) = value?.hashCode()
fun <T: Any> process2(value: T) = value.hashCode()
fun main(args: Array<String>) {
println(process<String?>(null)) // null
println(process2<String?>(null))
// Compile Error: Type Argument is not within its bounds.
}
type erasure
)<*>
List<?>
와 비슷하다.@Suppress("UNCHECKED_CAST")
fun printSum(c: Collection<*>) {
// Unchecked cast: Collection<*> to List<Int>
val intList = c as? List<Int>
?: throw IllegalArgumentException("List is expected")
println(intList.sum()) // 6
}
fun main(args: Array<String>) {
printSum(listOf(1, 2, 3))
// 6
printSum(setOf(1, 2, 3))
// IllegalArgumentException: List is expected
printSum(listOf("a", "b", "c"))
// ClassCastException: java.lang.String cannot be cast to java.lang.Number
}
is
검사 가능fun printSum(c: Collection<Int>) {
if (c is List<Int>) { // 이 검사는 올바르다.
println(c.sum())
}
}
fun main(args: Array<String>) {
printSum(listOf(1, 2, 3)) // 6
printSum(setOf(1, 2, 3)) // 출력없음.
}
<reified T>
로 선언해야 한다.inline
함수로 정의해야 한다.inline fun <reified T> isA(value: Any) = value is T
fun main(args: Array<String>) {
println(isA<String>("abc"))
println(isA<String>(123))
}