Kotlin Operators

Operators

The types of operators are as follows.

Arithmetic Operators (additiveOperator, multiplicativeOperator)

Arithmetic operators perform addition, subtraction, division, multiplication, and remainder operations.

expr1 + expr2         // Addition 
expr1 - expr2         // Subtraction 
expr1 * expr2         // Multiplication 
expr1 / expr2         // Division 
expr1 % expr2         // Remainder 

Assignment Operator

The assignment operator is used to put a value into a specific variable.

var = value           // Assignment 

Compound Assignment Operators

Compound assignment operators combine arithmetic operators and the assignment operator.

var += value          // Equivalent to var = var + value 
var -= value          // Equivalent to var = var - value 
var *= value          // Equivalent to var = var * value 
var /= value          // Equivalent to var = var / value 
var %= value          // Equivalent to var = var % value 

Positive, Negative, and Increment/Decrement Operators

Increment and decrement operators add or subtract 1 from a variable’s value.

+var                 // Positive
-var                 // Negative
var++                // Postfix increment operator (returns value before increment)
++var                // Prefix increment operator (returns incremented value)
var--                // Postfix decrement operator (returns value before decrement)
--var                // Prefix decrement operator (returns decremented value)

Comparison Operators (equalityOperator, comparisonOperator)

Comparison operators are used to compare the order, values, or objects of two variables.

expr1 == expr2       // Equal
expr1 != expr2       // Not equal
expr1 === expr2      // Same (reference comparison) 
expr1 !== expr2      // Not same (reference comparison) 
expr1 < expr2        // Less than
expr1 <= expr2       // Less than or equal
expr1 > expr2        // Greater than
expr1 >= expr2       // Greater than or equal

Logical Operators

Logical operators handle true and false values.

!expr1               // Negation (NOT) 
expr1 && expr2       // Logical AND 
expr1 || expr2       // Logical OR 

Array and Range Operators

arr[...]             // Refer to an array element 
*arr                 // Spread operator (expand array) 
n..m                 // Range
var in arr           // Contains 

Null-Safe Operators

var?.prop           // null if var is null; otherwise var.prop (safe call) 
var ?: expr         // var if var is not null; otherwise expr (Elvis operator) 
var!!               // Declare that var is not null

Referencing null is very dangerous. If you reference a null value, a NullPointerException occurs. Kotlin provides nullable types to prevent these kinds of exceptions from occurring.

fun moneyStatus(name: String, money: Int?): String? {
    return "$name 님의 재산은 ${money?:"0"}원 입니다."
}

fun main(args:Array<String>) {
    var name1: String = "devkuma" // non-null
    //name1 = null // error
    var name2: String? = "kotlin"
    name2 = null;

    println("name1.length = ${name1.length}")
    println("name2.length = ${name2?.length}")

    println(moneyStatus("kimkc",2000000000))
    println(moneyStatus("devkuma",null))

    val framework:String? = "spring"
    println(framework?.uppercase())

    val library:String? = null
    println(library?.uppercase())
    println(library!!.uppercase());
}
name1.length = 7
name2.length = null
kimkc 님의 재산은 2000000000원 입니다.
devkuma 님의 재산은 0원 입니다.
SPRING
null

? Operator

In Kotlin, a basic variable declaration cannot hold null. Therefore, assigning null to a normal variable causes a compile error. If you want to declare null, add a question mark (?) after the variable type to make it nullable.

var a:String? = null

This means that the value of a can be null.

var a:String = "devkuma"
var b:String = null
println(a.length) // 7
println(b?.length) // null

Since b is null, referencing b.length causes a NullPointerException. Writing b?.length returns null.

!! Operator

var b:String? = null
println(b!!.length) // NPE

If the value is not null, it returns that value; if it is null, a NullPointerException occurs.

Elvis (?:) Operator

var library:String? = null
println(library?.uppercase())
//println(library!!.uppercase())
println("Library ${library ?: "does not exist."}")

The Elvis operator is used similarly to a ternary operator. When a nullable variable returns null, you can specify a value to return instead of null.

The Elvis operator is named that way because if you rotate it 90 degrees to the right, the question mark (?) looks like hair and the colon (:) looks like eyes, resembling Elvis.

Lambda, Function, and Conditional Operators

args -> expr        // Lambda expression 
type1 -> type2      // Function type definition 
cond -> stmt        // when expression condition handling 

Other Operators

::func              // Function reference 
@annotation         // Annotation 
label@              // Label

Operator Precedence

Each operator has an execution order. When there are multiple operators, the order is determined by precedence.

Precedence Name Operator
Highest Postfix ++(postfix), --(postfix), ., ?., ?
2 Prefix -, +, ++(prefix), --(prefix), !, label
3 Type RHS :, as, as? (operators used to change types)
4 Multiplicative *, /, %
5 Additive +, -
6 Range .. (operator representing a range)
7 Infix function simpleIdentifier
8 Elvis ?:
9 Named checks in, !in, is, !is (used for range and type checks)
10 Comparison <, >, <=, >=
11 Equality ==, !=, ===, !==
12 Conjunction &&
13 Disjunction `
14 Spread operator *
Lowest Assignment =, +=, -=, *=, /=, %=

References