当前位置:网站首页>Kotlin interface generic covariant inversion
Kotlin interface generic covariant inversion
2022-06-24 13:35:00 【Hua Weiyun】
@[TOC](kotlin Interface Generic Covariance Inversion )
Preface
Use pure code Add The way of annotating , You can understand the source code faster
If you like , Please give me a compliment , In the later stage, we will continue to explain in depth
1、 Definition of interface
// All members in the interface and The interface itself , All are public open Of // An interface cannot have a primary construct // Implementing a class doesn't just rewrite the functions of the interface , The members of the interface should also be rewritten val mouse = Mouse() println(mouse.insertUBS()) val keyBoard = KeyBoard()// It can be changed at will set Value . keyBoard.usbInsertDevice = " Wang Wu " println(keyBoard.insertUBS())interface IUSB { var usbVersionInfo: String //USB Information about the relevant version var usbInsertDevice: String //USB Inserted device information fun insertUBS(): String // Insert UBS The implementation of the }// mouse USB The implementation of the class Mouse(override var usbVersionInfo: String = "USB 6.9", override var usbInsertDevice: String = " The mouse is inserted USB Interface ") : IUSB { override fun insertUBS(): String { return " The version number is :$usbVersionInfo Of $usbInsertDevice" }}// keyboard USB The implementation of the class KeyBoard : IUSB {// Below set ,get Will hold field, If you don't give usbVersionInfo assignment , signify field It's impossible to make set/get Held override var usbVersionInfo: String = " Advanced keyboard " get() = field set(value) { field = value } override var usbInsertDevice: String = " Access USB" get() { println(" You can get To $field Get your data out ") return field } set(value) { field = value println(" you set Came in $field Value ") } override fun insertUBS(): String { return " The content output of the keyboard is : $usbVersionInfo , $usbInsertDevice" }}2、 abstract class
// stay kotlin in , Abstract classes and Java Exactly the same val mainActivity = MainActivity() mainActivity.show()abstract class BaseActivity{ fun onCreate(){ setContentView(getLayoutID()) initView() initData() } private fun setContentView(layoutID: Int) = println(" load $layoutID Layout ") abstract fun getLayoutID(): Int abstract fun initView() abstract fun initData() fun show(){ onCreate() }}class MainActivity() : BaseActivity(){ override fun getLayoutID(): Int { return 662 } override fun initView() { return println(" load view") } override fun initData() { return println(" Load data ") }}3、 Define generic classes
// stay kotlin in , Definition of generics , and Java It doesn't make much difference Person(" Zhang San ").show() Person(11).show() Person(22.3f).show() Person(' male ').show()class Person<T> (private val obj: T){ fun show() = println(" I'm generic , What's your message , I can output $obj")}4、 Generic functions
println(Person(true, " Zhang San ").show()) println(Person(true, 11).show()) println(Person(false, 33.3f).show()) println(Person(false, ' male ').show())// Generic functions , Use Boolean To control whether the object returns , Application takeIf ( by true Just return the object itself ,false Just go back to null)class Person<T> (private val isR: Boolean, private val obj: T){ fun show() = obj.takeIf { isR }}5、 Generic transformation
val person = Person(true, " Student ") person.map { println(it) }class Person<T>(val isMap: Boolean = false, val inputType: T){// imitation RxJava T Is the input type to be transformed , R Is the type of output after transformation // map The returned type may be R, It could be null inline fun <R> map(mapAction: (T) -> R) = mapAction(inputType).takeIf { isMap }}6、 Generic type constraints
val person = Person("tiger", 88) val study = Study("tiger", 18) println(TextGeneric(person, true).show()) println(TextGeneric(study).show())open class MyAnyClass(name: String) { // Top level parent class }open class Person(name: String, age: Int) : MyAnyClass(name) {}class Study(name: String, age: Int) : Person(name, age) {}class Teacher(name: String, age: Int) : Person(name, age) {}class TextGeneric<T : Person>(private val inputTypeInfo: T, private val isR: Boolean = false) {// Universal returner fun show() = inputTypeInfo.takeIf { isR }}7、vararg keyword ( Dynamic parameters )
val p = Person("tiger", ' male ', 333, 32.5f, isR = true) println(p.showObject(1)) println(p.showObject(2)) println(p.showObject(3)) p.mapObject(1){ println(" convert to String $it") }class Person<T>(vararg objects: T, val isR: Boolean) { // objetArray: Array<T>// out Appoint T Can only read , Do not modify private val objectArray: Array<out T> = objects // showObject(index) fun showObject(index: Int) = objectArray[index].takeIf { isR } // mapObject(index Transform into Lambda) objectArray[index] fun <O> mapObject(index: Int, mapAction: (T) -> O) { mapAction(objectArray[index]) }}8、[] The operator
val p = Person("tiger", ' male ', 333, 32.5f, isR = true) println(p[1]) println(p[2]) println(p[3])class Person<T>(vararg objects: T, val isR: Boolean) { // objetArray: Array<T>// out Appoint T Can only read , Do not modify private val objectArray: Array<out T> = objects // operator Operator overloading , In use , You can use it directly [] Call it operator fun get(index: Int) = objectArray[index].takeIf { isR }}9、out Covariance & in Inversion Use
out Covariance : Parent class = Subclass
in Inversion : Subclass = Parent class
val setClass = SetClass<String>() println(setClass.setItem("tiger")) val getClass = GetClass(" Zhang San ") println(getClass.getItem())// in T Inversion 【 in T SetClass It can only be modified , change , Not accessible to the outside world 】class SetClass<in T>{ fun setItem(item: T): String { return " The data you want to set is :$item" }}// out T Covariance 【 out T GetClass Can be obtained , Read , Cannot be modified 】class GetClass<out T>(_item: T) { private val item: T = _item fun getItem(): T { return item }}summary
🤩
️
边栏推荐
- 金鱼哥RHCA回忆录:DO447管理项目和开展作业--为ansible剧本创建一个项目
- [one picture series] one picture to understand Tencent Qianfan apaas
- Getting started with the lvgl Library - colors and images
- CVPR 2022 - Interpretation of selected papers of meituan technical team
- "I, an idiot, have recruited a bunch of programmers who can only" Google "
- 物联网?快来看 Arduino 上云啦
- Perhaps the greatest romance of programmers is to commemorate their dead mother with a software
- Coinbase will launch the first encryption derivative for individual investors
- Use abp Zero builds a third-party login module (I): Principles
- Brief introduction to cluster analysis
猜你喜欢

3. caller service call - dapr

使用 Abp.Zero 搭建第三方登录模块(一):原理篇

Creation and use of unified links in Huawei applinking

开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低

Use abp Zero builds a third-party login module (I): Principles

敏捷之道 | 敏捷开发真的过时了么?
![[data mining] final review (sample questions + a few knowledge points)](/img/90/a7b1cc2063784fb53bb89b29ede5de.png)
[data mining] final review (sample questions + a few knowledge points)

Sinomeni vine was selected as the "typical solution for digital technology integration and innovative application in 2021" of the network security center of the Ministry of industry and information te

YOLOv6:又快又准的目标检测框架开源啦

黄金年代入场券之《Web3.0安全手册》
随机推荐
【AI玩家养成记】用AI识别邻居家旺财是什么品种
Geological disaster early warning monitoring RTU
SAP QM qac1 transaction code cannot modify the quantity in the inspection lot containing Hu
Memory introduction
华为 PC 逆势增长,产品力决定一切
Opengauss kernel: simple query execution
How can junior middle school developers effectively reduce their own workload?
Getting started with the lvgl Library - colors and images
RAID5 array recovery case tutorial of a company in Shanghai
kotlin 匿名函数 与 Lambda
CVPR 2022 | 美团技术团队精选论文解读
Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization
CPU status information us, sy and other meanings
3. Caller 服务调用 - dapr
8 lines of code to teach you how to build an intelligent robot platform
Can inspection results be entered after the completion of inspection lot UD with long-term inspection characteristics in SAP QM?
Vipshop's "special sale" business is no longer easy to do?
39 - read XML node and attribute values
On the difference between process and thread
kotlin 语言特性