val authors = listOf("Dmitry", "Svetlana")
컴파일러는 자동으로 author의 타입이 List임을 추론함
빈 리스트를 정의할 때는 타입 인자를 명시해줘야 함
val readers: MutableList<String> = mutableListOf() // 변수 타입 지정
val readers = mutableListOf<String>() // 함수 타입 지정
// slice함수 예시
fun <T> List<T>.slice(indices: IntRange) : List<T>
fun main() {
val letters = ('a'..'z').toList()
println(letters.slice<Char>(0..2))
// [a, b, c]
println(letters.slice(10..13))
// [k, l, m, n]
}
// 함수 시그니처
fun <T> List<T>.filter(predicate: (T) -> Boolean): List<T>
fun main() {
val authors = listOf("Sveta", "Seb", "Roman", "Dima")
val readers = mutableListOf("Seb", "Hadi")
println(readers.filter { it !in authors })
// [Hadi]
}
// 모든 List 타입에 대한 확장 파라미터
val <T> List<T>.penultimate: T
get() = this[size - 2]
fun main() {
println(listOf(1, 2, 3, 4).penultimate) // 파라미터 타입이 Int로 추론됨
//3
}
interface List<T> {
operator fun get(index: Int): T
/* ... */
}
// 구체적인 타입 지정
class StringList : List<T> {
override fun get(index: Int): String = this[index]
/* ... */
}
// 제네릭 타입 파라미터를 List의 타입 인자로 넘김
class ArrayList<T>: List<T> {
override fun get(index: Int): T = this[index]
/* ... */
}
// Comparable 인터페이스 구현 예제
interface Comparable<T> {
fun compareTo(other: T): Int
}
class String : Comparable<String> {
override fun compareTo(other: String): Int = TODO()
}
// 상계 지정 방법
fun <T : Number> List<T>.sum(): T
fun main() {
println(ListOf(1, 2, 3, 4).sum())
// 10
}
fun <T:Number> oneHalf(value: T): Double {
return value.toDouble() / 2.0
}
fun main() {
println(oneHalf(3))
// 1.5
}
fun <T: Comparable<T>> max(first: T, second: T): T {
return if (first > second) first else second
}
fun main() {
println(max("kotlin", "java"))
//kotlin
}
println(max("kotlin", 42))
// ERROR: Type parameter bound for T is not satisfied:
// inferred type Any is not a subtype of Comparable<Any>
fun <T> ensureTrailingPeriod(seq: T) where T : CharSequence, T : Appendable { // 타입 파라미터 제약 목록
if(!seq.endWith('.')) { // CharSequence 인터페이스의 확장 함수 호출
seq.append(.) // Appendable 인터페이스에 정의된 메서드 호출
}
}
fun main() {
val helloWorld = StringBuilder("Hello World")
ensureTrailingPeriod(helloWorld)
println(helloWorld)
//Hello World.
}
class Processor<T: Any> {
fun process(value: T) {
value.hashCode()
}
}