当前位置:网站首页>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
🤩
️
边栏推荐
- Integrate the authorization interface code of intra city distribution account of multiple express companies nationwide - Express 100
- 美国会参议院推进两党枪支安全法案
- One article explains R & D efficiency! Your concerns are
- 工业物联网(IIoT)的八个主要趋势
- CVPR 2022 | 美团技术团队精选论文解读
- I have fundamentally solved the problem of wechat occupying mobile memory
- CVPR 2022 | 美团技术团队精选论文解读
- Why does the kubernetes environment require that bridge NF call iptables be enabled?
- Definition and use of constants in C language
- C语言中常量的定义和使用
猜你喜欢

Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)

我真傻,招了一堆只会“谷歌”的程序员!

青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”

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

Several common DoS attacks

数据科学家面临的七大挑战及解决方法

一文讲透研发效能!您关心的问题都在

Teach you how to use airtestide to connect your mobile phone wirelessly!

Internet of things? Come and see Arduino on the cloud

DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中
随机推荐
MySQL interview questions
Nifi from introduction to practice (nanny level tutorial) - environment
The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
#yyds干货盘点# 解决剑指offer:调整数组顺序使奇数位于偶数前面(二)
Redis scenario
"Interesting" is the competitiveness of the new era
How to create a new empty branch in the web development process of easyrtc?
Implement Domain Driven Design - use ABP framework - update operational entities
Kubernetes集群部署
kotlin 继承、类、重载
Without home assistant, zhiting can also open source access homekit and green rice devices?
DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中
[data mining] final review (sample questions + a few knowledge points)
一文讲透研发效能!您关心的问题都在
如何化解35岁危机?华为云数据库首席架构师20年技术经验分享
Explain the difference between iaas/paas/saas by cooking rice
开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
8 lines of code to teach you how to build an intelligent robot platform
CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan