Article Directory
1. The variable parameter vararg keyword is used in combination with generics
If the parameter of the generic type T is a vararg variable parameter, when receiving the variable parameter, it needs to use a variable of type Array<out T> to receive;
The parameter is a vararg variable parameter, so multiple instance objects of the specified type can be passed in;
In the following code, the generic , and the T type does not have to be a subclass type of the Weapon class;
In the main constructor of Soldier, a variable parameter object of generic type ;
If you want to use member properties to receive variable parameter objects of the generic T type, you must use Array<out T> type objects to receive;
Code example:
class Soldier<T : Weapon>(vararg _items: T) {
var items: Array<out T> = _items
fun fight(){
for (item in items) {
item.fire()
}
}
}
open class Weapon(var name: String){
open fun fire(){
println("weapon fire !")
}
}
class AK47: Weapon("AK47"){
override fun fire(){
super.fire()
println("AK47 fire fire !")
}
}
class T72: Weapon("T72"){
override fun fire(){
super.fire()
println("T72 fire fire !")
}
}
fun main() {
var soldier: Soldier<Weapon> = Soldier(AK47(), T72())
soldier.fight()
}
Results of the :
weapon fire!
AK47 fire fire !
weapon fire!
T72 fire fire !
2. Use the [] operator to obtain the specified variable parameter object
If you want to use the [] operator to obtain the specified variable parameter object , you need to rewrite the get function of this class to perform operator overloading;
If you want Soldier 实例对象
to []
get one items: Array<out T>
of , you need to override the get
method of this class;
var items: Array<out T> = _items
operator fun get(index: Int): T? {
return items[index]
}
Then use soldier[0]
to get items
the instance object in the variable parameter;
var soldier: Soldier<Weapon> = Soldier(AK47(), T72())
soldier[0]?.fire()
soldier[1]?.fire()
Code example:
class Soldier<T : Weapon>(vararg _items: T) {
var items: Array<out T> = _items
operator fun get(index: Int): T? {
return items[index]
}
fun fight(){
for (item in items) {
item.fire()
}
}
}
open class Weapon(var name: String){
open fun fire(){
println("weapon fire !")
}
}
class AK47: Weapon("AK47"){
override fun fire(){
super.fire()
println("AK47 fire fire !")
}
}
class T72: Weapon("T72"){
override fun fire(){
super.fire()
println("T72 fire fire !")
}
}
fun main() {
var soldier: Soldier<Weapon> = Soldier(AK47(), T72())
soldier[0]?.fire()
soldier[1]?.fire()
}
Results of the :
weapon fire!
AK47 fire fire !
weapon fire!
T72 fire fire !