当前位置:网站首页>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
边栏推荐
- HCIP BGP lab report
- [MySQL Advanced] Creation and Management of Databases and Tables
- start with connect by implements recursive query
- Nine ways to teach you to read the file path in the resources directory
- noip初赛
- utils timer
- log4j-slf4j-impl cannot be present with log4j-to-slf4j
- [b01lers2020]Life on Mars
- Conditional Statements for Shell Programming
- Cisco ike2 IPSec configuration
猜你喜欢
重发布实验报告
[b01lers2020]Life on Mars
Network basic learning series four (network layer, data link layer and some other important protocols or technologies)
noip preliminary round
老板:公司系统太多,能不能实现账号互通?
2022的七夕,奉上7个精美的表白代码,同时教大家快速改源码自用
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!
Cisco ike2 IPSec configuration
override learning (parent and child)
Cloud platform construction solutions
随机推荐
utils timer
网络基础学习系列四(网络层,数据链路层和一些其他重要协议或技术)
物联网新零售模式,引领购物新潮流
授人以渔 - 如何自行查询任意 SAP UI5 控件属性的文档和技术实现细节试读版
HDU 5655 CA Loves Stick
Adobe是什么?
PowerMockup 4.3.4::::Crack
【day6】类与对象、封装、构造方法
完全二叉树问题
Cloud platform construction solutions
October 2019 Twice SQL Injection
What is Adobe?
Canvas App中点击图标生成PDF并保存到Dataverse中
Makefile
2019年10月SQL注入的两倍
伴随着元宇宙、web3.0等概念的兴起,数字人、数字场景等诸多数字化的形态开始出现
代码随想录笔记_动态规划_416分割等和子集
【bug】汇总Elipse项目中代码中文乱码解决方法!
Conditional Statements for Shell Programming
Summary bug 】 【 Elipse garbled solution project code in Chinese!