当前位置:网站首页>Kotlin foundation extension
Kotlin foundation extension
2022-06-13 06:25:00 【m0_ forty-seven million nine hundred and fourteen thousand one 】
One . spread function
1. Define universal extension functions
The extension can be in Add class functions without directly modifying class definitions , Extensions can be used to customize classes , It can also be used for example List、String, as well as Kotlin Other classes in the standard library . Similar to inheritance , Extensions can also share class behavior , stay You can't touch a class definition , Or a class doesn't use open Modifier , When you can't inherit it , Extension is the best choice to add class functions .
// Custom extension function , stay String Back panel !
fun String.addExt(amount :Int =1)=this+"!".repeat(amount)
// Define extension functions on superclasses
fun Any.easyPrint(): Any {
print("$this \n")
return this
}
fun main() {
print("abc".addExt(2))
15.easyPrint()
}
2. Define generic extension functions
Generic extension functions can not only support any type of receiver , It also retains the type information of the recipient , After using generic types , The extension function can support more types of receivers , Wider application .
// Custom extension function
fun String.addExt(amount :Int =1)=this+"!".repeat(amount)
// Generic extension function
fun <T> T.easyPrint(): T{
print("$this \n")
return this
}
fun main() {
print("abc".addExt(2))
"xiaohua".easyPrint().addExt().easyPrint().addExt()
15.easyPrint()
"The people' s Republic of China".numVowels.easyPrint()
}
Generic extension functions in Kotlin The standard library is everywhere , for example let function ,let Functions are defined as generic extension functions , So it can support any type , It receives a lambda expression , This lambda Expression receiver T As a value parameter , Back to R—lambda Any new type returned by the expression .
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}
Two . Extended attributes
1. Extended attributes
In addition to adding function extension functions to classes , You can also define extended properties for classes .
// Custom properties
val String.numVowels
get() = count{"aeiou".contains(it)}
// Generic extension function
fun <T> T.easyPrint(): T{
print("$this \n")
return this
}
fun main() {
"The people' s Republic of China".numVowels.easyPrint()
}
2. Nullable class extension
Define extension functions for nullable types , Define extension functions on nullable types , You can directly solve the possible null value problem in the extension function body .
fun String?.printWithDefault(default:String?)= print(this?:default)
fun main() {
val nullableString:String?=null
nullableString.printWithDefault("abc")
}
3.infix keyword
infix Keywords apply to extensions and class functions with a single parameter , It allows you to call functions in a more concise syntax , If a function definition uses infix keyword , So when you call it , Point operations between the receiver and the function and a pair of parentheses for parameters can be omitted .
infix fun String?.printWithDefault(default:String?)= print(this?:default)
fun main() {
val nullableString:String?=null
nullableString printWithDefault "abc"
}
4. Define extension file
The extension function needs to be used in multiple files , It can be defined in a separate file , then import.
package com.example.kotiln_a
fun <T> Iterable<T>.randomTake() :T =this.shuffled().last()
import com.example.kotiln_a.randomTake
fun main() {
listOf("1","2","3").randomTake().easyPrint()
}
5. Rename extension
occasionally , You want to use an extension or a class , But its name doesn't agree with you .
import com.example.kotiln_a.Extension as randomTake
fun main() {
listOf("1","2","3").randomTake().easyPrint()
}
6.Kotlin Extensions in the standard library
Kotlin Many of the functions provided by the standard library are By extending functions and attributes Of , Standards that contain class extensions
Library files are usually added with the class name s Suffix , for example Sequences.kt, Ranges.kt, Maps.kt.
3、 ... and .DSL
1. Function literal of the receiver to be received
// spread function
fun String.addExt() = "!".repeat(count())
// Extension functions of generics
fun <T> T.easyPrint(): Unit = println(this)
// Why should I pass in an extension function ( Generic ), Instead of an ordinary anonymous function ?
//T.() -> Unit
// The extension function has its own receiver object this Implicit call
// Why are generic extension functions ?
// Anonymous functions , It can also be an extension function
// Ordinary anonymous functions
//() -> Unit
// Inside anonymous functions this Point to one File object , Implicit call
//File.() -> Unit
/*public inline fun <T> T.apply(block: T.() -> Unit): T {
block()
return this
}
*/
public inline fun File.apply(block: File.() -> Unit): File {
block()
return this
}
fun main() {
val file = File("xx").apply {
setReadable(true)
}
// Break it down here
//1. Define extension functions
fun File.ext(): Unit {
setReadable(true)
}
//2. to block Variable assignment
val block = File::ext
//3. Pass in apply function
File("xx").apply { block }
}
2.DEL
Use this programming paradigm , You can write the well-known " Domain specific language "(DSL), A kind of API Programming
normal form , Expose the receiver's functions and features , So that you can use the |ambda Expressions to read and configure them .
边栏推荐
- Wechat applet uploads pictures (preview deletion limits the size and number of pictures)
- Vector control of Brushless DC motor (4): sensorless control based on sliding mode observer
- View绘制整体流程简析
- Detailed explanation of PHP distributed transaction principle
- Wechat applet (function transfer parameters, transfer multiple parameters, page Jump)
- [DP 01 backpack]
- 【MySQL】基础知识小复习
- Fragment lifecycle
- Applet disable native top
- 二分查找
猜你喜欢
Echart折线图:多条折线图每次仅展示一条
微信小程序:点击事件获取当前设备信息(基础)
本地文件秒搜工具 Everything
Download and installation of universal player potplayer, live stream m3u8 import
【新手上路常见问答】一步一步理解程序设计
JVM Foundation
Rk3399 hid gadget configuration
Echart柱状图:堆叠柱状图value格式化显示
[2022 college entrance examination season] what I want to say as a passer-by
SSM框架整合--->简单后台管理
随机推荐
Solution: vscode open file will always overwrite the last opened label
杨辉三角形详解
Wechat applet (get location)
[written examination questions of meituan]
【美团笔试题】
App performance test: (II) CPU
Wechat applet custom tabbar (session customer service) vant
Recent problems
Omron Ping replaces the large domestic product jy-v640 semiconductor wafer box reader
Solutions to common problems in small program development
Notifyitemchanged flash back
SSM框架整合--->简单后台管理
El form form verification
Echart柱状图:echart实现堆叠柱状图
Applet export (use) public function, public data
Download and installation of universal player potplayer, live stream m3u8 import
Echart折线图:多条折线图每次仅展示一条
不在以下合法域名列表中,微信小程序解决办法
USB status error and its cause (error code)
SSM framework integration -- > simple background management