Introduction to Operator Overloading
Explore operator overloading and learn how to use custom operators in classes.
We'll cover the following...
In Kotlin, we can add an element to a list using the +
operator. In the same way, we can add two strings together. We can check if a collection contains an element using the in
operator. We can also add, subtract, or multiply elements of type BigDecimal
, which is a JVM class that is used to represent possibly big numbers with unlimited precision.
Press + to interact
import java.math.BigDecimalfun main() {val list: List<String> = listOf("A", "B")val newList: List<String> = list + "C"println(newList) // [A, B, C]val str1: String = "AB"val str2: String = "CD"val str3: String = str1 + str2println(str3) // ABCDprintln("A" in list) // trueprintln("C" in list) // falseval money1: BigDecimal = BigDecimal("12.50")val money2: BigDecimal = BigDecimal("3.50")val money3: BigDecimal = money1 * money2println(money3) // 43.7500}
...