当前位置:网站首页>Kotlin keyword extension function
Kotlin keyword extension function
2022-06-24 13:35:00 【Hua Weiyun】
@[TOC](kotlin keyword spread function )
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、reified keyword
// 1、 Create three new data classes , Used to randomly generate objects // 2、randomOrDefault() function , Backup mechanism Lambda// 3、 Randomly generate one object // <ObjectClass1> Specified objects TestClass().randomOrDefault<ObjectClass1> { println(" Due to randomly generated objects It's different from what we specified , Enable alternate objects ") ObjectClass1(" Alternate objects , King five ", 99) }data class ObjectClass1(val name: String, val age: Int)data class ObjectClass2(val name: String, val age: Int)data class ObjectClass3(val name: String, val age: Int)class TestClass {// All functions , It's all written on the function // By default, an object is output randomly , If this object is inconsistent with the specified object , Enable alternate objects , Otherwise, the object is returned directly inline fun <reified T> randomOrDefault(defaultLambdaAction:() ->T) : T? { val objList = listOf( ObjectClass1("obj1 tiger", 18), ObjectClass2("obj2 Zhang San ", 38), ObjectClass3("obj3 Wang Meili ", 28) )// Randomly select the last object val randomObj = objList.shuffled().last() println(" The randomly generated object is :$randomObj")// If it The generated object is equal to T The type of , Will go as T Straight back return randomObj.takeIf { it is T } as T? // null as T null as T?// If it Randomly generated objects It's not equal to T type , Just go straight to the spare section below ?: defaultLambdaAction() }}2、 Define extension functions
stay kotlin in , There are many extensible functions , Here are a few examples :
ObjectClass1(" Zhang San ", 22).show() ObjectClass1("tiger", 22).getInfo() println("tiger".addExtAction(3))// Add extension function show()fun ObjectClass1.show(){ println(" I'm new show function :name: $name, age:$age")}// Add extension function getInfo()fun ObjectClass1.getInfo(){ println(" I'm new getInfo function :name: $name, age:$age")}// character string Expand fun String.addExtAction(number: Int) = this + "@".repeat(number)data class ObjectClass1(val name: String, val age: Int)3、 Nullable type function extension
"tiger".outPutStringValue(" Pass on null Just go here ") null.outPutStringValue(" Pass on null Just go here ")// String When it cannot be empty , Can only pass values , In the case of nullable , It can be transmitted null// defaultValue Add an alternate function , The value passed in is null Under the circumstances , return defaultValue Alternate content fun String?.outPutStringValue(defaultValue: String){ println(this ?: defaultValue)}4、infix keyword
infix Infix expression , It simplifies the code . Need to add Extension functions can only be used
// Conditions for a : For the first parameter O1.test() Function extension // Condition 2 : Need to be in Brackets (o2: o2) In the parameters , Pass a parameter "tiger".test("18") "tiger" test ("18") 123 test ("18")// map Comes with infix expressions val mapOf = mapOf("tiger" to 2) println(mapOf)infix fun <O1, O2> O1.test(o2: O2) { println(" The content of the first parameter of infix expression is :$this") println(" The content of the second parameter of infix expression is :$o2")}5、 Transform function Map
// principle : Is to put Anonymous functions The return value of the last line , Add to a new collection , The generic type of the new set is R, And return the set val listOf = listOf(" Zhang San ", " Wang Meili ", " It's beautiful ") val map = listOf.map { "[$it]" }.map { " What do you give , I dare to add $it" } println(map)6、 Transform function flatMap
// principle : Is to put Anonymous functions The return value of the last line , Add to a new collection , The generic type of the new set is R, And return the set val listOf = listOf(" Zhang San ", " Wang Meili ", " It's beautiful ") val map = listOf.map { "[$it]" // One at a time string }.flatMap { listOf("$it What do you give = I dare to add ","$it To express dissatisfaction with ","$it I think Wang is beautiful and ugly ") // Return one set at a time } println(map)7、filter Filter function
// filter The function is very simple to use , But it has to be a collection val listOf1 = listOf(" Zhang San ", " Wang Meili ", " It's beautiful ") val listOf2 = listOf(" Zhang s", " Liu Fang ", " Wang Wu ") val ls2 = listOf(listOf1, listOf2) val map = ls2.flatMap { it -> it.filter { it.contains(' Zhang ') } }// The output is an array , The elements are only contain contains(' Zhang ') Of println(map)8、 Merge operators
// principle : Is to put a collection and The second set combined , Create a new collection , And back to // Create a new collection ( Elements , Elements , Elements ) Elements Pair(K, V) Instead of the first set element V Replace the elements of the second set val listOf1 = listOf(" Zhang San ", " Wang Meili ", " It's beautiful ") val listOf2 = listOf(45, 18, 21) val zip = listOf1.zip(listOf2) println(zip)// Traverse zip.forEach { println(" Name is :${it.first} Age is :${it.second}") } zip.toMap().forEach{ k, v -> println(" Name is :${k} Age is :${v}") }9、 Add kotlin Implementation of single case
//kotlin Implementation of the singleton pattern class KotlinInstance private constructor() { companion object { val instance: KotlinInstance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { KotlinInstance() } } fun show(){ println("show") }}summary
🤩
️
边栏推荐
- #yyds干货盘点# 解决剑指offer:调整数组顺序使奇数位于偶数前面(二)
- DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中
- Integrate API interface parameter Dictionary of accounts of multiple local distribution companies - Express 100
- Hands on data analysis unit 3 model building and evaluation
- 服务可见可观测性
- Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)
- ERR AUTH&lt; password&gt; called without anypassword configured for the default user. Ar
- kotlin 协程 lanch 详解
- I have fundamentally solved the problem of wechat occupying mobile memory
- Parti,谷歌的自回归文生图模型
猜你喜欢

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

Kubernetes集群部署

Getting started with the go Cobra command line tool

"Interesting" is the competitiveness of the new era

Party, Google's autoregressive Wensheng graph model

Getting started with the lvgl Library - colors and images

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

Main steps of system test

The agile way? Is agile development really out of date?

我从根上解决了微信占用手机内存问题
随机推荐
Implement Domain Driven Design - use ABP framework - update operational entities
kotlin 初始化块
3. Caller 服务调用 - dapr
Android kotlin 大全
硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
CPU status information us, sy and other meanings
Use abp Zero builds a third-party login module (I): Principles
金鱼哥RHCA回忆录:DO447管理项目和开展作业--为ansible剧本创建一个项目
CVPR 2022 - Interpretation of selected papers of meituan technical team
初中级开发如何有效减少自身的工作量?
I have fundamentally solved the problem of wechat occupying mobile memory
Comparator sort functional interface
Implement Domain Driven Design - use ABP framework - create entities
源码解析 Handler 面试宝典
Understanding openstack network
青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
Parti,谷歌的自回归文生图模型
ERR AUTH&lt; password&gt; called without anypassword configured for the default user. Ar
C语言中常量的定义和使用
天猫618农产品“百强县” 35个县域来自中西部及东北