当前位置:网站首页>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
🤩
️
边栏推荐
- 强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
- LVGL库入门教程 - 颜色和图像
- Can inspection results be entered after the completion of inspection lot UD with long-term inspection characteristics in SAP QM?
- 实现领域驱动设计 - 使用ABP框架 - 更新操作实体
- 8 lines of code to teach you how to build an intelligent robot platform
- 这几个默认路由、静态路由的配置部署都不会,还算什么网工!
- 发扬连续作战优良作风 全力以赴确保北江大堤安全
- 不用Home Assistant,智汀也开源接入HomeKit、绿米设备?
- Use abp Zero builds a third-party login module (I): Principles
- Redis scenario
猜你喜欢

3. caller service call - dapr

Definition and use of constants in C language

Opengauss kernel: simple query execution

DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中

Without home assistant, zhiting can also open source access homekit and green rice devices?

首席信息安全官仍然会犯的漏洞管理错误

Developer survey: rust/postgresql is the most popular, and PHP salary is low

如何避免严重网络安全事故的发生?
![[data mining] final review (sample questions + a few knowledge points)](/img/90/a7b1cc2063784fb53bb89b29ede5de.png)
[data mining] final review (sample questions + a few knowledge points)

Main steps of system test
随机推荐
"Interesting" is the competitiveness of the new era
LVGL库入门教程 - 颜色和图像
Developer survey: rust/postgresql is the most popular, and PHP salary is low
物联网?快来看 Arduino 上云啦
Google Earth Engine——1999-2019年墨累全球潮汐湿地变化 v1 数据集
I have fundamentally solved the problem of wechat occupying mobile memory
Cloud native essay solicitation progress case practice
谁是鱼谁是饵?红队视角下蜜罐识别方式汇总
Comparator 排序函数式接口
黄楚平主持召开定点联系珠海工作视频会议 坚决落实省委部署要求 确保防疫情、稳经济、保安全取得积极成效
青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
Memory introduction
使用 Abp.Zero 搭建第三方登录模块(一):原理篇
kotlin 初始化块
Nifi from introduction to practice (nanny level tutorial) - environment
About the hacked database
Internet of things? Come and see Arduino on the cloud
我从根上解决了微信占用手机内存问题
Several common DoS attacks
Kubernetes集群部署