package com.av.bcacc.kotlinpai.api.basic.study
import kotlin.reflect.KProperty
/**
* @description 泛型
* @author wlhu
* @time 2022/12/3 16:54
* @email:2072025612@qq.com
*/
class KotlinGeneric {
var p by Delegate()
fun deal(){
p = 123
println("代理方法p= "+p)
}
}
class MyClass<T> {
fun deal(param: T): T {
return param
}
}
class MyClass2 {
//非泛型类的泛型方法
fun <T> deal(param: T): T {
return param;
}
//给泛型指定类型
fun <T : Number> deal2(param: T): T {
return param
}
}
/**
* @description 委托模式:这种方法如果需要重写的方法比较多就不适用了
* @author wlhu
* @time 2022/12/4 19:29
* @email:2072025612@qq.com
*/
class MySet<T>(val helperSet: HashSet<T>) : Set<T> {
override val size: Int
get() = helperSet.size
override fun contains(element: T): Boolean {
return helperSet.contains(element)
}
override fun containsAll(elements: Collection<T>): Boolean {
return helperSet.containsAll(elements)
}
override fun isEmpty(): Boolean {
return helperSet.isEmpty()
}
override fun iterator(): Iterator<T> {
return helperSet.iterator()
}
}
/**
* @description Kotlin中委托使用by关键字,这样代码就简化许多,如果确实需要重写某个方法对单个方法重写就可以了
* @author wlhu
* @time 2022/12/4 19:32
* @email:2072025612@qq.com
*/
class MySetNew<T>(var helperSet: HashSet<T>) : Set<T> by helperSet {
override fun isEmpty(): Boolean {
return false;
}
}
class Delegate {
var propValue: Any? = null
//第一个参数表示可以在哪个类中调用
operator fun getValue(kotlinGeneric: KotlinGeneric, prop: KProperty<*>): Any? {
return propValue
}
operator fun setValue(kotlinGeneric: KotlinGeneric, prop: KProperty<*>,value: Any?) {
propValue = false
}
}
fun main() {
println("hello kotlin")
println("##########################Kotlin 泛型类的使用####################")
var myClass = MyClass<Int>()
println("myClass deal result:" + myClass.deal(123))
var myClass2 = MyClass2()
println("myClass2 deal result:" + myClass2.deal("hello"))
println("调用指定类型的方法myClass2 deal result:" + myClass2.deal2(567))
println("##########################Kotlin 委托的使用####################")
var mKotlinGeneric = KotlinGeneric()
mKotlinGeneric.deal()
}
Kotlin 泛型学习
最新推荐文章于 2025-12-22 22:11:34 发布
1127

被折叠的 条评论
为什么被折叠?



