- 泛型,即 “参数化类型”,将类型参数化,可以用在类,接口,方法上
- 泛型,为类型安全提供保证,消除类型强转的烦恼
1、示例
定义
class Box<T> constructor(t: T) {
var value: T = t
init {
var str = when (t) {
is Int -> "Int"
is Float -> "Float"
is Double -> "Double"
is Long -> "Long"
is String -> "String"
is Any -> "Any"
else -> "don't know"
}
Log.i("TAG_ZLZ", "------ value 的类型 : $str, 其值为 : $t")
}
}
使用
- 如果可以推断出类型参数,可以省略泛型参数
val any = Any()
val b1 = Box<Int>(1001)
val b2 = Box(78.987)
val b3 = Box("test")
val b4 = Box(any)
日志输出
2、泛型约束
定义类
class Employer constructor(name: String, position: String) : Comparable<Employer> {
companion object {
const val MANAGER = "manager"
const val WORKER = "worker"
}
/**
* mName 姓名
* mPosition 职位
*/
private val mName: String = name
private val mPosition: String = position
override fun compareTo(other: Employer): Int {
val curPosition = when (mPosition) {
MANAGER -> 2
WORKER -> 1
else -> 0
}
val otherPosition = when (other.mPosition) {
MANAGER -> 2
WORKER -> 1
else -> 0
}
return curPosition.compareTo(otherPosition)
}
fun showInfo() {
Log.i("TAG_ZLZ", "------ 姓名 : $mName, 职位 : $mPosition")
}
}
比较方法
fun <T> comparePosition(e1: T, e2: T): T? where T : Comparable<T> {
return when {
e1 > e2 -> {
e1
}
e1 < e2 -> {
e2
}
else -> {
null
}
}
}
使用
val e1 = Employer("Alex", Employer.MANAGER)
val e2 = Employer("Kim", Employer.WORKER)
comparePosition(e1, e2)?.showInfo()
日志输出