728x90
package generic
fun main() {
val t1 = TestClass1<Int>()
t1.testMethod1(100)
val t2 = TestClass1<String>()
t2.testMethod1("dfdf")
val t3 = TestClass2<Int>(100)
t3.testMethod(200)
}
class TestClass1<T> {
fun testMethod1(a1:T){
println("a1 = ${a1}")
}
}
class TestClass2<T>(var a1: T){
fun testMethod(a2: T) {
println("a1 = ${a1}")
println("a2 = ${a2}")
}
}
// 불변성
// 제네릭 타입에 부모 클래스를 담을수 없다
class TestClass5<A>()
// 공변성
// 제테릭 타입에 부모 클래스를 담을 수 있다
class TestClass6<out A>()
// 반 공변성
// 제네릭 타입에 자식클래스를 담을 수 있다 (부모 타입 못담음)
// 주로 사용하지 않음
class TestClass7<in A>()
728x90
'언어 > Kotlin' 카테고리의 다른 글
코틀린 null 처리 (0) | 2022.05.25 |
---|---|
코틀린 익명 중첩 클래스 (0) | 2022.05.25 |
코틀린 DataClass (0) | 2022.05.25 |
코틀린 Companion (0) | 2022.05.24 |
코틀린 지연 초기화 (0) | 2022.05.24 |