当前位置:网站首页>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
🤩
️
边栏推荐
- Implement Domain Driven Design - use ABP framework - create entities
- Best practices of swagger in egg project
- Summary of the process of restoring damaged data in MySQL database
- Cloud native essay solicitation progress case practice
- Redis scenario
- 金鱼哥RHCA回忆录:DO447管理清单和凭据--为访问清单主机创建机器凭据
- Integrate the authorization interface code of intra city distribution account of multiple express companies nationwide - Express 100
- One hour is worth seven days! Ingenuity in the work of programmers
- kotlin 匿名函数 与 Lambda
- 天猫618农产品“百强县” 35个县域来自中西部及东北
猜你喜欢

Getting started with the lvgl Library - colors and images

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

AGCO AI frontier promotion (6.24)

Hands on data analysis unit 3 model building and evaluation

Comparator sort functional interface

Getting started with the go Cobra command line tool

LVGL库入门教程 - 颜色和图像

这几个默认路由、静态路由的配置部署都不会,还算什么网工!

One article explains R & D efficiency! Your concerns are

Use abp Zero builds a third-party login module (I): Principles
随机推荐
工业物联网(IIoT)的八个主要趋势
Hands on data analysis unit 3 model building and evaluation
青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
CVPR 2022 | 美团技术团队精选论文解读
RAID5 array recovery case tutorial of a company in Shanghai
Best practices of swagger in egg project
I enlighten a friend and my personal understanding of the six patriarchs' Tan Jing
黄楚平主持召开定点联系珠海工作视频会议 坚决落实省委部署要求 确保防疫情、稳经济、保安全取得积极成效
LVGL库入门教程 - 颜色和图像
kotlin 协程 lanch 详解
CPU process priority
The second phase of freshman engineering education seminar is to enroll in the China 100 school peer program
Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan
System status identifier 'hum' for SAP QM inspection lot
Brief introduction to cluster analysis
How to create a new empty branch in the web development process of easyrtc?
Several common DoS attacks
How long will it take to open a mobile account? Is online account opening safe?
Yolov6: the fast and accurate target detection framework is open source