当前位置:网站首页>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 .
边栏推荐
- Learning records countless questions (JS)
- 电镀挂具RFID工序管理解决方案
- App performance test: (II) CPU
- [MySQL] basic knowledge review
- Uniapp secondary encapsulates uview components, and the parent component controls display and hiding
- 华为开发者认证与DevEco Studio编译器下载
- 推荐扩容工具,彻底解决C盘及其它磁盘空间不够的难题
- Failed to extract manifest from apk: processexception:%1 is not a valid Win32 Application.
- Logcat -b events and eventlogtags print the location correspondence of the events log in the code
- High burst solution 2
猜你喜欢

杨辉三角形详解

欧姆龙平替国产大货—JY-V640半导体晶元盒读写器

Recommend a capacity expansion tool to completely solve the problem of insufficient disk space in Disk C and other disks

Failed to extract manifest from apk: processexception:%1 is not a valid Win32 Application.

楊輝三角形詳解

RN Metro packaging process and sentry code monitoring

SSM integration

RFID process management solution for electroplating fixture

Echart line chart: multiple line charts show only one line at a time

SSM framework integration -- > simple background management
随机推荐
Analysis of 43 cases of MATLAB neural network: Chapter 10 classification of discrete Hopfield Neural Network -- evaluation of scientific research ability of colleges and Universities
JVM基础
The title of the WebView page will be displayed in the top navigation bar of the app. How to customize
Vector control of Brushless DC motor (4): sensorless control based on sliding mode observer
Thread correlation point
Relationship between fragment lifecycle and activity
Echart rectangular tree diagram: simple implementation of rectangular tree diagram
Basic knowledge of knowledge map
Wechat applet (pull-down refresh data) novice to
Echart折线图:当多条折线图的name一样时也显示不同的颜色
PHP redis makes high burst spike
Fichier local second Search Tool everything
AI realizes "Resurrection" of relatives | old photo repair | old photo coloring, recommended by free app
Download and installation of universal player potplayer, live stream m3u8 import
Wechat applet uploads pictures (preview deletion limits the size and number of pictures)
JS to realize bidirectional data binding
Solutions to common problems in small program development
‘ipconfig‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
Multiple reception occurs in the uniapp message delivery
[2022 college entrance examination season] what I want to say as a passer-by