当前位置:网站首页>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
🤩
️
边栏推荐
- AGCO AI frontier promotion (6.24)
- 青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
- kotlin 关键字 扩展函数
- 初中级开发如何有效减少自身的工作量?
- nifi从入门到实战(保姆级教程)——环境篇
- #云原生征文#Ingress案例实战
- 强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
- LVGL库入门教程 - 颜色和图像
- The introduction of MySQL memory parameters is divided into two categories: thread exclusive and global sharing
- 敏捷之道 | 敏捷开发真的过时了么?
猜你喜欢

CVPR 2022 | 美团技术团队精选论文解读

Internet of things? Come and see Arduino on the cloud

Kubernetes cluster deployment

Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization

不用Home Assistant,智汀也开源接入HomeKit、绿米设备?

Getting started with the go Cobra command line tool

Brief introduction to cluster analysis

物联网?快来看 Arduino 上云啦

Several common DoS attacks

Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team
随机推荐
金鱼哥RHCA回忆录:DO447管理项目和开展作业--为ansible剧本创建一个项目
Cloud native essay solicitation progress case practice
Party, Google's autoregressive Wensheng graph model
Richard Sutton, the father of reinforcement learning, paper: pursuing a general model for intelligent decision makers
Definition and use of constants in C language
8 - Format integers and floating point numbers
Integrate the authorization interface code of intra city distribution account of multiple express companies nationwide - Express 100
LVGL库入门教程 - 颜色和图像
Internet of things? Come and see Arduino on the cloud
敏捷之道 | 敏捷开发真的过时了么?
Sphere, openai and ai21 jointly publish the best practice guidelines for deployment models
Nifi from introduction to practice (nanny level tutorial) - environment
Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)
Geological disaster early warning monitoring RTU
RAID5 array recovery case tutorial of a company in Shanghai
工业物联网(IIoT)的八个主要趋势
Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team
Comparator 排序函数式接口
Yyds dry goods counting solution sword finger offer: adjust the array order so that odd numbers precede even numbers (2)
I enlighten a friend and my personal understanding of the six patriarchs' Tan Jing