当前位置:网站首页>Kotlin - extension functions and operator overloading
Kotlin - extension functions and operator overloading
2022-08-03 22:46:00 【m0_63970488】
I. Extension function
Extension function means that the class can still be opened and new functions can be added to the class without modifying the source code of the class.
The following is an example of a function. For example, a string may contain characters, numbers and special characters. Now we want to count the number of letters in the string. How to implement this function?Refer to a piece of code:
object StringUtil {fun lettersCount(str: String): Int {var count = 0for (c in str) {if (c.isLetter()) {count++}}return count}}
val str = "[email protected]#"val lettersCount = StringUtil.lettersCount(str)
This way of writing can definitely work, and this is also the most standard implementation thinking in the JAVA language.After there are extension functions in Kotlin, it is different. For example, in Kotlin, the lettersCount() function can be added to the String class.
Let's refer to the syntax structure of the extension function:
fun ClassName.methodName(param1: Int, param2: Int): Int {return 0}
Compared with defining an ordinary function, the extension function only needs to add a syntax structure of ClassName. in front of the function name, which means that the function is added to the specified class.
Below we are writing by String class distance, so we need to create a String.kt file first.Although there is no fixed requirement for the file name, the author recommends adding an extension function to that class, and defining a Kotlin file with the same name, which is convenient for later searching. The extension function can be defined in any existing class, and does not have to be created.New files, usually we better define it as a top-level method, which is convenient for global access.
fun String.lettersCount(): Int {var count = 0;for (c in this) {if (c.isLetter()) {count++}}return count}
We define the lettersCount method as an extension function of String, then the function will automatically have the context of the String instance, so the lettersCount function does not need to accept a string parameter.Just traverse this directly.
After defining the extension function, the number of letters in a certain string can be counted as follows:
val str = "[email protected]#".lettersCount()
Second, operator overloading
Many languages have built-in operator keywords in Java, such as: +-*/%++ --.And Kotlin allows us to overload all operators and even other keywords, thus extending the usage of these operators and keywords.
The operator keyword is used by the keyword of operator overloading. As long as the operator keyword is added in front of the specified function, the function of operator overloading can be realized.But the question is what is this specified function?This is a more complicated problem in operator overloading, because the overloaded functions corresponding to different Yusheng Nanfu are also different. For example, the plus operator corresponds to the plus() function, and the minus operator corresponds to the minus() function..
If two objects implement the addition function, then its grammatical structure is as follows:
class Obj {operator fun plus(obj: Obj){// handle the addition logic}}
The keywords operator and plus are both fixed, and the function return value of the cutting parameter can be set according to the logic, then the above code means that an Obj object can be added to another Obj object, and finally returns a newThe Obj object.
val obj1 = Obj()val obj2 = Obj()val obj3 = obj1 + obj2
The following defines the addition of two Money objects. First, define the structure of the Money class. Here, let the main constructor of Money accept a value parameter, which is used to represent the amount of money. Create the Money.kt file
class Money(val value: Int) {operator fun plus(money: Money): Money {val sum = money.valuereturn Money(sum)}}
As you can see, the operator keyword is used here to modify the plus() function, which is essential.In the plus() function, we add the current Money and object value to the value of the Money object passed in as a parameter, and then pass the resulting sum to a new Money object and return the object.The two Moneys can be added together.
val money1 = Money(5)val money2 = Money(10)val money3 = money2 + money1Log.d("TAG", "initData: $money3")
The final result printed is 15.
It would be better if the Money object was added directly to the number.Of course this function is also possible.Because Kotlin allows us to multiple overload the same operator, the code is as follows:
class Money(val value: Int) {operator fun plus(money: Money): Money {val sum = money.valuereturn Money(sum)}operator fun plus (newValue:Int):Money{val sum = value+newValuereturn Money(sum)}}
Here is another overloaded plus() function, which accepts an integer number, and the other codes are basically the same:
val money1 = Money(5)val money2 = Money(10)val money3 = money2 + money1val monet4 = money3 + 20Log.d("TAG", "initData: $monet4")
Kotlin allows us to overload many operators and keywords, please execute the query
边栏推荐
- Quickly build a website with static files
- Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan
- Zilliz 2023 秋季校园招聘正式启动!
- encapsulation, package, access modifier, static variable
- win10系统下yolov5-V6.1版本的tensorrt部署细节教程及bug修改
- Embedded Systems: Clocks
- "Digital Economy Panorama White Paper" Financial Digital User Chapter released!
- Canvas App中点击图标生成PDF并保存到Dataverse中
- 目标检测技术研究现状及发展趋势
- 工作小计 QT打包
猜你喜欢
Adobe是什么?
2022-08-03 oracle执行慢SQL-Q17对比
pikachu Over permission
2022-08-02 mysql/stonedb慢SQL-Q18-内存使用暴涨分析
Gains double award | know micro easily won the "2021 China digital twin solution suppliers in excellence" "made in China's smart excellent recommended products" double award!
node连接mysql数据库报错:Client does not support authentication protocol requested by server
嵌入式系统:时钟
生成器版和查看器版有什么区别?
Cisco ike2 IPSec configuration
Embedded systems: overview
随机推荐
Codeup brushing notes - simple simulation
Adobe是什么?
CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应
【MySQL进阶】数据库与表的创建和管理
Conditional Statements for Shell Programming
Teach a Man How to Fish - How to Query the Properties of Any SAP UI5 Control by Yourself Documentation and Technical Implementation Details Demo
pikachu Over permission 越权
网络基础学习系列四(网络层,数据链路层和一些其他重要协议或技术)
FinClip最易用的智能电视小程序
重发布实验报告
Golang Chapter 1: Getting Started
utils timer
[b01lers2020]Life on Mars
一个函数有多少种调用方式?
为什么我们需要回调
关于IDO预售系统开发技术讲解丨浅谈IDO预售合约系统开发原理分析
Bytebase database schema change management tool
AOSP CameraLatencyHistogram的原理与使用
2022-08-02 mysql/stonedb slow SQL-Q18 - memory usage surge analysis
Summary bug 】 【 Elipse garbled solution project code in Chinese!