当前位置:网站首页>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 + obj2The 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
边栏推荐
- 优化查询(工作中)
- Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan
- 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!
- Fluorescein-PEG-CLS,胆固醇-聚乙二醇-荧光素科研试剂
- websocket多线程发送消息报错TEXT_PARTIAL_WRITING--自旋锁替换synchronized独占锁的使用案例
- 重发布实验报告
- 嵌入式系统:GPIO
- RPA助力商超订单自动化!
- Cisco ike2 IPSec配置
- for循环练习题
猜你喜欢

静态文件快速建站

亿流量大考(2):开发一套高容错分布式系统

嵌入式系统:GPIO

Boss: There are too many systems in the company, can you realize account interoperability?

Embedded Systems: GPIO

Pytest学习-setup/teardown
![[b01lers2020]Life on Mars](/img/d0/d5c9b7224542c8843ce29adc7ef713.png)
[b01lers2020]Life on Mars
![navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication](/img/09/a579c60e07cdc145175e72673409f7.png)
navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication

Click the icon in Canvas App to generate PDF and save it to Dataverse

如何创建一个Web项目
随机推荐
Why do we need callbacks
The development status of cloud computing at home and abroad
LabVIEW code generation error 61056
2022-08-03 Oracle executes slow SQL-Q17 comparison
On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use
Conditional Statements for Shell Programming
UVa 1025 - A Spy in the Metro(白书)
log4j-slf4j-impl cannot be present with log4j-to-slf4j
2022-08-02 mysql/stonedb慢SQL-Q18-内存使用暴涨分析
log4j-slf4j-impl cannot be present with log4j-to-slf4j
Embedded Systems: Clocks
LabVIEW代码生成错误 61056
October 2019 Twice SQL Injection
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
What is the difference between the generator version and the viewer version?
navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication
Makefile
优化查询(工作中)
HDU 5655 CA Loves Stick
Nine ways to teach you to read the file path in the resources directory