当前位置:网站首页>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 .
边栏推荐
- MFS详解(七)——MFS客户端与web监控安装配置
- Explication détaillée du triangle Yang hui
- Recent problems
- 【美团笔试题】
- Omron Ping replaces the large domestic product jy-v640 semiconductor wafer box reader
- Analysis of 43 cases of MATLAB neural network: Chapter 11 optimization of continuous Hopfield Neural Network -- optimization calculation of traveling salesman problem
- 无刷直流电机矢量控制(四):基于滑模观测器的无传感器控制
- 动态链接库嵌套样例
- Waterfall flow layout of uni app Homepage
- After clicking the uniapp e-commerce H5 embedded applet, the page prompts "the page iframe does not support referencing non business domain names"
猜你喜欢
Recommend a capacity expansion tool to completely solve the problem of insufficient disk space in Disk C and other disks
JS to realize bidirectional data binding
Analysis of 43 cases of MATLAB neural network: Chapter 11 optimization of continuous Hopfield Neural Network -- optimization calculation of traveling salesman problem
Free screen recording software captura download and installation
Wechat applet: click the event to obtain the current device information (basic)
Custom view - extensible collapsexpendview
Echart柱状图:echart实现堆叠柱状图
Echart line chart: different colors are displayed when the names of multiple line charts are the same
Echart rectangular tree diagram: simple implementation of rectangular tree diagram
The web server failed to start Port 7001 was already in use
随机推荐
MFS詳解(七)——MFS客戶端與web監控安裝配置
pthon 执行 pip 指令报错 You should consider upgrading via ...
Relationship between fragment lifecycle and activity
View绘制整体流程简析
Wechat applet (function transfer parameters, transfer multiple parameters, page Jump)
Wechat applet jumps to H5 page with parameters
[JS] array de duplication
Fichier local second Search Tool everything
《MATLAB 神经网络43个案例分析》:第10章 离散Hopfield神经网络的分类——高校科研能力评价
App performance test: (III) traffic monitoring
Recyclerview has data flicker problem using databinding
Echart折线图:当多条折线图的name一样时也显示不同的颜色
微信小程序:全局状态变量的使用
Echart矩形树图:简单实现矩形树图
IOError(Errors.E050.format(name=name))
【MySQL】基础知识小复习
Uniapp mobile terminal uses canvas to draw background convex arc
Custom view
电镀挂具RFID工序管理解决方案
Time complexity and space complexity