Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of overloading Kotlin operator

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this "Kotlin operator overloading method" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Kotlin operator overloading method" article.

Arithmetic operator overload

I define a class in kotlin

Data class Point (val x: Int, val y: Int)

Then instantiate two objects

Val p1 = Point (3p5) val p2 = Point (5p7)

Want to represent the element x of p1 plus the element x of p2, the element y of p1, and the element y of p2. Then output a p3.

Val p3 = Point (p1.x + p2.x, p2.y + p2.y)

There is nothing wrong with the above way of writing. However, we can use the Kotlin extension function to simplify the above operation, we add a plus to Point, and append the operator keyword. (the keyword operator is added to distinguish that plus is not a normal member method.)

Data class Point (val x: Int, val y: Int) {operator fun plus (other: Point): Point {return Point (x + other.x, y + other.y)}}

Next, let's realize the above requirements.

Val p3 = p1 + p2

The expression is more concise this way. In addition, we can use plus as an extension of Point.

Data class Point (val x: Int, val y: Int) operator fun Point.plus (other: Point): Point {return Point (x + other.x, y + other.y)}

This scenario applies when Point exists in a three-party library, and we can modify its contents. Overloading of the following operators is provided in Kotlin. You only need to implement the corresponding method.

Before we ordered a plus, the parameter is Point, in fact, for an operator overload is not limited to the same type, then let's define a times, which allows you to extend Ponit.

Data class Point (val x: Int, val y: Int) operator fun Point.times (scale: Double): Point {return Point ((x * scale). ToInt (), (y * scale). ToInt ()} fun main (args: Array) {val p = Point (10,20) println (p * 1.5)}

Note that kotlin does not support interchangeability, for example, 1.5 * p is not allowed here. Unless you order one.

Operator fun Double.times (p: Point): Point

The return type can also be different from the same type, for example, define a duplicate count for the char type overload * operator and return a string.

Operator fun Char.times (count: Int): String {return toString () .repeat (count)} fun main (args: Array) {println ('a' * 3)} compound operator overload

We usually write this simplified way of writing p = p + p1 as p + = p1 in the programming process, and we also support this custom operation of the + = operator in kotlin. In what scenarios is this custom operation operator used? For example, let's define a set

Val numbers = ArrayList () numbers + = 42println (numbers [0])

The above writing will feel more concise. We define the operator overload method plusAssign in the collection (there are also minusAssign, timesAssign, and so on)

Operator fun MutableCollection.plusAssign (element: t) {this.add (element)}

However, the kotlin-stblib library has helped you to implement similar operations on collections. In the collection, +,-will accumulate the original collection and return a new collection. If you use + =,-=, the collection is mutable, it will modify the content directly in this collection. If the collection is read-only, it will return a copied modified collection. This means that if the collection is read-only, its declaration must be var, otherwise it cannot accept a newly returned copy of the modified collection. You can use individual elements or collections (the type must be consistent) for composite operator operations and arithmetic operators.

Val list = arrayListOf (1,2) list + = 3 val newList = list + listOf (4,5) println (list) result: [1,2,3] println (newList) result: [1,2,3,4,5] unary operator overload

We also support operator overloading when we use things like + a, aura,-- a, a-m-m in the programming process. You just need to rewrite the following operator function

For instance

Operator fun BigDecimal.inc () = this + BigDecimal.ONEfun main (args: Array) {var bd = BigDecimal.ZERO println (bd++) println (+ + bd)}

Notice here that I only order an inc (), which also supports bd++ and + + bd.

Comparison operator overload

Kotlin also supports = =,! =, >, and x 1-> y else-> throw IndexOutOfBoundsException ("Invalid coordinate $index")}} fun main (args: Array) {val p = Point (10,20) println (p [1])}

We can also use custom operator for assignment operations.

Data class MutablePoint (var x: Int, var y: Int) operator fun MutablePoint.set (index: Int, value: Int) {when (index) {0-> x = value 1-> y = value else-> throw IndexOutOfBoundsException ("Invalid coordinate $index")} fun main (args: Array) {val p = MutablePoint (10,20) p [1] = 42 println (p)}

Another knowledge point is the custom in operator

In determines whether an element belongs to a range or not for the contains function.

Data class Point (val x: Int, val y: Int) data class Rectangle (val upperLeft: Point, val lowerRight: Point) operator fun Rectangle.contains (p: Point): Boolean {return p.x in upperLeft.x until lowerRight.x & & p.y in upperLeft.y until lowerRight.y} fun main (args: Array) {val rect = Rectangle (Point (10,20), Point (50,50) println (Point (20,30) in rect) println (Point (5) 5) in rect)} iterative operator overloading

What we usually use.

For (x in list) {...}

Will be converted to a call to list.iterator (), and then call the hasNext and next methods repeatedly, just as in Java. Note that in Kotlin, it is also a convention, which means that iterator methods can be defined as extensions. This explains why regular Java strings can be iterated: kotlin-stblib defines an extended function iterator on Char-Sequence (the superclass of String):

Operator fun CharSequence.iterator (): CharIterator > > for (c in "abc") {}

Other types can also implement their own class-specific operations through custom iterator.

Import java.util.Dateimport java.time.LocalDateoperator fun ClosedRange.iterator (): Iterator = object: Iterator {var current = start override fun hasNext () = current > > val p = Point (10,20) > val (x, y) = p > println (x) 10 > println (y) 20

The deconstructing declaration looks a bit like a variable declaration, but it combines multiple variable values. In fact, it is also a custom operator in kotlin. To deconstruct multiple variables, you need to define where componentN,N is a variable.

Class Point (val x: Int, val y: Int) {operator fun component1 () = x operator fun component2 () = y}

For the data class, deconstruction has already declared for you that additional deconstruction declarations can also be used in loops

Fun printEntries (map: Map) {for ((key, value) in map) {println ("$key-> $value")} fun main (args: Array) {val map = mapOf ("Oracle" to "Java", "JetBrains" to "Kotlin") printEntries (map)}

Map contains the extension method component1,component2 that returns key and value. In fact, you can translate the loop above into

For (entry in map.entries) {val key = entry.component1 () val value = entry.component2 () / /.} above is the content of this article on "methods of overloading Kotlin operators". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report