泛型
泛型概念和java中的泛型是一致的,没有特别的地方
定义
这里包含有定义和使用,和java中的泛型是一样的想法
fun BaseMain() {
Table<String>("NieBin")
}
class Table<TYPE> constructor(t: TYPE) {
init {
println("This is $t")
}
}
可转变
这和
fun BaseMain() {
var dog = Dog("Black")
var cat = Cat("小黄")
var animal: Animal = dog
println("The name is ${animal.name}")
animal = cat
println("This name is ${animal.name}")
}
class Table<TYPE> constructor(t: TYPE) {
init {
println("This is $t")
}
}
open class Animal(name: String) {
var name = "";
init {
this.name = name
}
}
class Dog(name: String) : Animal(name) {
}
class Cat(name: String) : Animal(name) {
}
协变
在java中 String 是Object的子类,但是List<String>是不能转换为List<Object>的,但是在kotlin中却可以这样,如果一个类是另外一个类的子类,那么就可以像普通子类父类之间进行转换赋值了,如下
fun BaseMain() {
var dogs: List<Dog> = listOf(Dog("A"), Dog("B"))
var animals: List<Animal> = dogs
for (animal in animals) {
println("This animal's name is ${animal.name}")
}
}
open class Animal(name: String) {
var name = "";
init {
this.name = name
}
}
class Dog(name: String) : Animal(name) {
}
class Cat(name: String) : Animal(name) {
}
就像普通类一样,是不是很爽
逆向转变
在泛型中,就是可以将父类型转换为子类型的操作
fun BaseMain() {
val animal: Compare<Animal> = object : Compare<Animal> {
override fun compare(t: Animal) {
println("This is animal compare and name is ${t.name}")
}
}
val dogCompare: Compare<Dog> = animal
dogCompare.compare(Dog("This is black."))
}
open class Animal(name: String) {
var name = "";
init {
this.name = name
}
}
class Dog(name: String) : Animal(name) {
}
interface Compare<in T> {
fun compare(t: T)
}
参考文章 讲得特别清晰明白