当前位置:网站首页>Kotlin base generics
Kotlin base generics
2022-06-13 06:25:00 【m0_ forty-seven million nine hundred and fourteen thousand one 】
One . Generic classes
1. Definition
The constructor of a generic class can accept any type .
// Generic
class MagicBox<T>(item : T) {
var available =false;
private var subject:T =item
}
class Box(val name:String,val age:Int)
class Man(val name:String,val age:Int)
fun main() {
val box1:MagicBox<Box> = MagicBox(Box(" Xiaohua ", 20))
val box2:MagicBox<Man> = MagicBox(Man(" Xiaohua ", 10))
}MagicBox Class specifies that the generic parameters are placed in a pair <> The letters in T Express ,T It's a representative item Placeholder for type .MagicBox Class accepts any type of item As the main constructor value (item :T), And will item Value assigned to the same T Type of subject Private property .
Two . Generic functions
1. Generic functions
Generic parameters can also be used for functions .
class MagicBox<T>(item : T) {
var available =false;
private var subject:T =item
fun fetch():T?{
return subject.takeIf { available }
}
}
class Box(val name:String,val age:Int)
class Man(val name:String,val age:Int)
fun main() {
val magicBox = MagicBox(Box(" Xiaohua ", 20))
magicBox.available=true
// Print
magicBox.fetch()?.run {
println("you find $name")
}
}
2. Multiple generic functions
Generic functions or generic classes can also have multiple generic parameters .
class MagicBox<T>(item : T) {
var available =false;
private var subject:T =item
fun fetch():T?{
return subject.takeIf { available }
}
// Here, a new class is passed in to replace the one passed in through the constructor
fun <R> fetch(SubjectModFunction:(T)->R) :R?{
return SubjectModFunction(subject).takeIf { available }
}
}
fun main() {
val magicBox = MagicBox(Box(" Xiaohua ", 20))
magicBox.available=true
// There's a lambda Expressions are used to pass values
val fetch = magicBox.fetch {
Man(" Xiaohua ", 30)
}
fetch?.let {
print("${it.name} ${it.age}")
}
}3、 ... and . Generic type constraints
1. Generic type constraints
Make sure that if MagicBox It can only contain specified types of items , Such as Human type , What do I do ?
class MagicBox<T: Human>(item : T) {
var available =false;
private var subject:T =item
fun fetch():T?{
return subject.takeIf { available }
}
}
fun main() {
val magicBox:MagicBox<Human> = MagicBox(Box(" Xiaohua ", 20))
}
2.vararg The key words and get function
MagicBox Can store any type of Human Solid column , But only one at a time , If you need to place multiple instances, you need to use vararg keyword
class ArrayMagicBox<T:Human>(vararg item : T) {
var available =false;
// Set generics
private var subject: Array<out T> =item
fun fetch(index : Int ): T? {
return subject[index].takeIf { available }
}
// This is the same as the previous one. It only adds a subscript to get values from the array
fun <R> fetch(index:Int, SubjectModFunction:(T)->R) :R?{
return SubjectModFunction(subject[index]).takeIf { available }
}
}
3.[ ] Operator value
Want to [ ] Operator value , Operator functions can be overloaded get Method .
class ArrayMagicBox<T:Human>(vararg item : T) {
var available =false;
// Set generics
private var subject: Array<out T> =item
// Call... By object get Method to get the specified subscript value
operator fun get(index: Int):T?=subject[index].takeIf { available }
fun fetch(index : Int ): T? {
return subject[index].takeIf { available }
}
// This is the same as the previous one. It only adds a subscript to get values from the array
fun <R> fetch(index:Int, SubjectModFunction:(T)->R) :R?{
return SubjectModFunction(subject[index]).takeIf { available }
}
}4.out
out( Covariance ), If a generic class only returns a generic type as a function ( Output ), So use out, It can be called production class / Interface , Because it's mainly used to produce (produce) The specified generic object .
interface Production<out T>{
fun product():T
}5.in
in( Inversion ), If a generic class only takes a generic type as an input parameter to a function ( Input ), So use in, It can be called a consumer / Interface , Because it's mainly for consumption (consume) The specified generic object .
interface Consumer<in T>{
fun consume(item : T)
}6. Why use in&out
A parent generic object can be assigned to a child generic object , use in
Subclass generic objects can be copied to parent generic objects , use out
7.invariant
If a generic class takes a generic type as a function parameter , The generic type is used as the output of the function , So neither out Also need not in.
interface ProductionConsumer< T>{
fun consume(item : T)
fun product():T
}8.reified
occasionally , You may want to know what type a generic parameter is ,reified Keyword can help you check the generic parameter type .Kotlin Generic parameters are not allowed T Do a type check , Because the generic parameter type will be erased by the type , in other words ,T The type information of is unknown at run time .
class MagicBoxReified<T:Human> (){
// inline Generic type inference
inline fun <reified T> randomOrBackup(backup:()->T):T{
val item= listOf(
Boy(" Xiaohua ",20),
Mna(" Xiaogang ",24)
)
val last = item.shuffled().last()
return if (last is T){
last
}else{
backup()
}
}
}
open class Human(val age:Int){
}
class Boy(val name:String,age: Int): Human(age){
override fun toString(): String {
return "$name $age"
}
}
class Mna(val name:String,age: Int):Human(age){
override fun toString(): String {
return "\n $name $age"
}
}
fun main() {
val magicBoxReified = MagicBoxReified<Human>()
val randomOrBackup = magicBoxReified.randomOrBackup {
Mna(" Xiaohong ", 30)
}
print(randomOrBackup)
}边栏推荐
- Echart line chart: when multiple lines have the same name, the legend is still displayed
- Simple use of event bus
- Fidde breakpoint interception
- MFS explanation (V) -- MFS metadata log server installation and configuration
- Intelligent digital asset management helps enterprises win the post epidemic Era
- 347. top k high frequency elements heap sort + bucket sort +map
- Local file search tool everything
- Recent problems
- Win10 drqa installation
- Huawei developer certification and deveco studio compiler Download
猜你喜欢
![[one · data 𞓜 simple implementation of the leading two-way circular linked list]](/img/a2/08f55012cd815190db76237f013961.png)
[one · data 𞓜 simple implementation of the leading two-way circular linked list]

Echart histogram: X-axis displays value, Y-axis displays category

Vector control of Brushless DC motor (4): sensorless control based on sliding mode observer

《MATLAB 神经网络43个案例分析》:第11章 连续Hopfield神经网络的优化——旅行商问题优化计算

Custom view - extensible collapsexpendview

Echart rectangular tree diagram: simple implementation of rectangular tree diagram

万能播放器 PotPlayer 的下载与安装,直播流 m3u8 导入

Recommend a capacity expansion tool to completely solve the problem of insufficient disk space in Disk C and other disks

1+1 > 2, share creators can help you achieve

‘ipconfig‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
随机推荐
SSM framework integration -- > simple background management
Download and installation of universal player potplayer, live stream m3u8 import
[written examination questions of meituan]
Notifyitemchanged flash back
Huawei developer certification and deveco studio compiler Download
Rk3399 hid gadget configuration
华为开发者认证与DevEco Studio编译器下载
Multiple reception occurs in the uniapp message delivery
Applet pull-up loading data
MFS詳解(七)——MFS客戶端與web監控安裝配置
Wechat applet (pull-down refresh data) novice to
杨辉三角形详解
Wechat applet custom tabbar (session customer service) vant
免费录屏软件Captura下载安装
JVM基础
端午安康,使用祝福话语生成词云吧
MFS详解(七)——MFS客户端与web监控安装配置
JS convert text to language for playback
【MySQL】基础知识小复习
MFS explanation (VI) -- MFS chunk server installation and configuration