1 unary operator

Unary operators include prefix operators, increment and decrement operators, etc.

1.1 Prefix operators

+, -,! These three, placed before the operands, correspond to the fixed methods shown in the table

The operator Corresponding method
+a a.unaryPlu()
+a a.unaryMinus()
! a a.not()

Sample code:

fun main(args: Array<String>) { var a = 20; // use the operator val b =-a; // call the method val c = a.naryminus (); println("b: ${b}, c: ${c}");
	val flag = true// Use the operator val notFlag1 =! Val notFlag2 = flag.not() println()"notFlag1: ${notFlag1}, notFlag2: ${notFlag2}");
}
Copy the code

It can be seen that the effect of -a and a.naryminus () is exactly the same; ! Flag has exactly the same effect as flag.not().

1.2 Increment and decrement operators

The autoadditive (++) and subtractive (–) operators and their corresponding fixed methods are shown in the table

The operator Corresponding method
a++ a.inc()
a– a.dec()

2 Binary operators

The binary operators in Kotlin include arithmetic operators, index access operators, call operators, calculate and assign operators, equality and inequality operators, Elvis operators, comparison operators, infix operators, and so on.

2.1 Arithmetic operators

Arithmetic operators addition, subtraction, multiplication, division, mod, range operators, etc

The operator Corresponding method
a + b a.plus(b)
a – b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b A. Em (b), A. mode (b)(mod obsolete)
a .. b a.rangeTo(b)

For example, the following procedure.

fun main(args: Array<String>) {// Add println(5 + 6) println(5. Plus (6)) // Multiply println(2.3 * 3.4) println(2.3. Times (3.4)) // Multiply Println (2.5%1.2) println(2.5.rem(1.2))}Copy the code

2.2 and in! The in operator.

And in! The in operator and its corresponding fixation methods are shown in the table

The operator Corresponding method
a in b b.contains(a)
a ! in b ! b.contains(a)

For example, the following procedure.

fun main(args: Array<String>) {
    var str = "hello java"Println (STR. Contains (STR."java")) / / useinOperator to determine println("java" inSTR) val array = arrayOf(24, 45, 100, -1, 30) // Call println(array.contains(100)) //true/ / useinThe operator determines println(100)in/ / output array)true
}
Copy the code

As you can see from the above code, Kotlin uses the IN operator because the contains() method with one argument exists in the String class.

2.3 Index access operators

Index access operators and their corresponding fixed methods are tables

The operator Corresponding method
a[i] a.get(i)
a[i] = b a.set(i, b)

For example, the following procedure.

fun main(args: Array<String>) {
    var str = "hello java"Println (str.get(2)) println(STR [2]) // Create a Java ArrayList collection var list = java.util.ArrayList<String>() list.add("Java")
    list.add("Kotlin")
    list.add("Go"Println (List [1]) println(List [1]) // Kotlin (List [2] ="Swift"
    println(list)
}
Copy the code

Since the String class provides the get(index) method, programs can retrieve characters at a given index using an index access operator like [2], whereas Java’s ArrayList provides the get(index) and set(index, val) methods. Therefore, a program can obtain or modify collection elements at a specified index through the index access operator.

2.4 Calling operators

The call operators and their corresponding fixed methods are shown in a table

The operator Corresponding method
a() a.invoke()
a(i) = b a.invoke(i)

For example, the following procedure.

fun main(args: Array<String>) {
    val s = "java.lang.String"Val MTD = class.forname (s).getMethod()"length"Println (mtd.invoke(invoke)) // Invoke (mtd.invoke)"java"Println (MTD (println(MTD ()))"java") // Output 4}Copy the code

Because the Method class provides the invokeO Method, a program can either call the invoke() Method in the traditional Java way or call it directly using the invocation operator.

2.5 Calculate and assign operators

The operator Corresponding method
a += b a.plusAssign(b)
a -= b a.minusAssign(b)
a *= b a.timesAssign(b)
a /= b a.divAssign(b)
a %= b a.remAssign(b)

2.6 The equality and inequality operators

The operator Corresponding method
a == b a? .equals(b) ? : (b === null)
a ! = b ! (a? .equals(b) ? : (b === null)))

There are two types of equality in Kotlin:

  1. Reference equality ===! == (two references to the same object)
  2. Structure equality ==,! = (check with equals()).
fun main(args: Array<String>) {
    var s1 = java.lang.String("java")
    var s2 = java.lang.String("java") println(s1 == s2); / / outputtrue1) println (s1) equals (s2)); / / outputtrue(2) the println (s1 = = = s2); / / outputfalseprintln(s1 ! == s2); / / outputtrue
}
Copy the code

The essence of ① and ② above is the same. Java provides “==” and “! = “in Kotlin is made up of” === “and”! == “instead.

2.7 Comparison operators

All comparison expressions in Kotlin are converted to calls to the compareTo() function, which returns an Int value.

The operator Corresponding method
a > b a.compareTo(b) > 0
a < b a.compareTo(b) < 0
a >= b a.compareTo(b) >= 0
a <= b a.compareTo(b) <= 0

The comparison operator is used to compare the size of the String and Date classes. Since the two classes implement the Comparable interface, it is perfectly acceptable to use the comparison operator to compare sizes (especially for numeric types). Kotlin will convert the size comparison operator to compareTo().

Thus, when programming with Kotlin, instances of a class that implements the Comparable interface can use the comparison operator to compare sizes.

3 bit operator

Although Kotlin also provides bitwise operators that do exactly what Java does, none of these bitwise operators are given in the form of functions rather than special characters, so programs can only execute these bitwise operators using function names.

Kotlin also supports the following seven bitwise operators.

  1. And: indicates the bitwise and. Returns 1 when both digits are 1.
  2. Or: bitwise or. If one of them is 1, you can return 1.
  3. Inv: indicates bitwise non. Unary operator that inverts every bit of the operand, including the sign bit.
  4. Xor: xOR by bit. Returns 0 if two digits are the same, 1 if not.
  5. SHL: left-shift operator.
  6. SHR: right shift operator.
  7. Ushr: Unsigned right-shift operator.

Kotlin’s bitwise operators work only on Int and Long.

Interval operator

Kotlin provides two interval operators, the closed interval operator and the half-open interval operator, both of which make it very convenient to build a data structure that can contain all the values within a particular interval.

4.1 Closed interval operators

The closed interval operator a.. B is used to define an interval of all values from A to B, including a and B boundary values. For closed interval operators, a cannot be greater than b, or the program will run with an error.

4.2 Half-open interval operators

The half-open interval operator a until b is used to define an interval of all values from A to B, including the a boundary values, but not the B boundary values. The half-open interval operator is similar to the closed interval operator in that a cannot be greater than b.

If the values of boundary A and boundary B are equal in **a until B ** *, an empty interval will be generated that contains no values;

If a.. If the value of boundary A is equal to that of boundary B in B, an interval containing only one value will be generated, and the interval containing only one boundary value will be generated.

Fun main(args: Array<String>) {use the closed interval operator to define the interval,forVar range1 = 2.. 4for (num in range1) {
        println("${num} * 5 = ${num * 5}"Val books = arrayOf("Swift"."Kotlin"."C"."C++") // Use the half-open query operator to define an interval, which is handy when iterating over lists of numbers (array elements whose index is 0 to length minus 1)for (index in 0 until books.size) {
        println("The first${index + 1}The languages are:${books[index]}")}}Copy the code

Output:

2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 1 is Swift 2 is Kotlin 3 is C 4 is C++Copy the code

4.3 Reverse Interval

If a program wants the interval to go from large to small, it can use the downTo operator, which also builds a closed interval. For a downTo B, b must not be greater than A. For example, the following program defines the reverse interval using downTo.

Fun main(args: Array<String>) {var range1 = 3 downTo 1for (num in range1) {
        println("${num} * 5 = ${num * 5}")}}Copy the code

Output:

3 times 5 is 15, 2 times 5 is 10, 1 times 5 is 5Copy the code

4.4 Interval step size

The step operator allows you to explicitly specify the step size of the interval. For example:

Fun main(args: Array<String>) {// Specify the step size for the reverse closed intervalfor (num in 7 downTo 1 step 3) {
        println("${num} * 5 = ${num * 5}")}}Copy the code

Output:

7 times 5 is 35. 4 times 5 is 20. 1 times 5 is 5Copy the code

5 Operator overloading

Kotlin’s operators are supported by methods with specific names, so we can add these operators to any class by overloading methods with those names. Methods that overload an operator need to be marked with an operator modifier.

5.1 Overloading unary prefix operators

A program can use +, -,! On instances of any class as long as it defines methods named unaryPlus(), unaryMinus(), or not() with operator modifier. Unary prefix operator. For example, the following procedure.

The above program defines a not() method for the Data class as an extension method. This method also returns a Data instance that inverts the x and y attributes of Data. This means that we can apply “! “to the Data instance. This unary prefix operator.

The last two lines of the main() method apply “-” and “! “to the Data object. The output of these two operators, these two expressions is the same.

5.2 Overloading the add and subtract operators

Data class data (val x: Int, val y: Int) {// Define an inc() method for data class. Operator fun inc(): data {returnData(x + 1, y + 1)}} dee () operator fun data.dec (): Data {returnData(x - 1, y - 1) } fun main(args: Array<String>) {var d = Data(4, 10) println(d++) Data(x=4, y=10) println(d) var dd = Data(9, 20) println(--dd) Data (x=8, y=19) println(dd) : Data (x=8, y=19)}Copy the code

The above program defines operators for the Data class in the form of normal and extended methods, so the program can then perform operations on Data instances using the autoadd and subtraction operators.

When the program uses the self-addition operator on a Data object, the x and y attributes of the object will be incremented by 1. When a program uses the decrement operator on a Data object, both the x and y properties of the object are decayed by 1. The difference between ++ and — before and after a variable is exactly the same as the difference between ++ and — after a variable in the Java language.

5.3 Overloading binary arithmetic operators

Data class Point(val x: Int, val y: Int) {// Define a minus() method for the Point class. Operator fun minus(target: Point): Double {returnMath.hypot((this.x-target.x).todouble (), (this.y-target.y).todouble ())}} // Define the Point class as an extension methodtimesOperator fun Point. Times (target: Point): Int {operator fun Point.return Math.abs(this.x - target.x) *
            Math.abs(this.y - target.y)
}

fun main(args: Array<String>) {
    var p1 = Point(4, 10)
    var p2 = Point(5, 15)
    var distance = p1 - p2;
    println("The distance between P1 and P2 is:${distance}")
    var area = p1 * p2
    println("The rectangular area of P1 and P2 is:${area}")}Copy the code

Output:

The distance between PL and P2 is 5.0990195135927845. The area of a rectangle enclosing PL and P2 is 5Copy the code

A Point class is defined in the above program. The next program defines a minus() method in the Point class, which is used to calculate the distance between two points. In addition, the program defines a times() method for the Point class in the form of an extension method that calculates the area of the rectangle between the two points.

Once minus() and times() are defined for the Point class, the program can then use the – and * operators to calculate the distance between the two operators and the area of the rectangle.

6 Other operators

  1. The colon operator (:) is used for declarations of variable or constant types, as well as declarations of inherited parent classes and implementation interfaces
  2. The parentheses (()) change the order in which expressions are evaluated, and have the highest precedence
  3. Brackets ([]) index access operation symbol
  4. Reference Number (.) Invoke a function or property operator
  5. Assignment (=) Assignment is done using the equal operator
  6. Nullable (?) Identifies a nullable type
  7. The safe call operator (? .). Calls a function or property of a non-null type
  8. The Elvis operator (? 🙂 null value merge operator
  9. Non-empty assertions (!!) Asserts that nullable expressions are non-null
  10. The double colon (::) refers to a class, attribute, or function
  11. Interval (..) Represents a range range
  12. The arrow (->) is used to declare Lambda expressions
  13. The expansion operator (*) is used when passing arrays to mutable arguments