Arithmetic Operators in Kotlin Hindi
Here's a list of arithmetic operators in Kotlin:
| Operator | Meaning |
|---|---|
| + | Addition (also used for string concatenation) |
| - | Subtraction Operator |
| * | Multiplication Operator |
| / | Division Operator |
| % | Modulus Operator |
Example: Arithmetic Operators
fun main(args: Array<String>) {
val number1 = 12.5
val number2 = 3.5
var result: Double
result = number1 + number2
println("number1 + number2 = $result")
result = number1 - number2
println("number1 - number2 = $result")
result = number1 * number2
println("number1 * number2 = $result")
result = number1 / number2
println("number1 / number2 = $result")
result = number1 % number2
println("number1 % number2 = $result")
}
When you run the program, the output will be:
number1 + number2 = 16.0 number1 - number2 = 9.0 number1 * number2 = 43.75 number1 / number2 = 3.5714285714285716 number1 % number2 = 2.0
The
+ operator is also used for the concatenation of String values.Example: Concatenation of Strings
fun main(args: Array<String>) {
val start = "Talk back. "
val middle = "Show me the code. "
val end = "- kotlin is good"
val result = start + middle + end
println(result)
}
When you run the program, the output will be:
Talk is cheap. Show me the code. - Linus Torvalds
How arithmetic operators actually work?
Suppose, you are using
+ arithmetic operator to add two numbers a and b.
Under the hood, the expression
a + b calls a.plus(b) member function. The plus operator is overloaded to work with String values and other basic data types (except Char and Boolean).// + operator for basic types operator fun plus(other: Byte): Int operator fun plus(other: Short): Int operator fun plus(other: Int): Int operator fun plus(other: Long): Long operator fun plus(other: Float): Float operator fun plus(other: Double): Double // for string concatenation operator fun String?.plus(other: Any?): String
You can also use
+ operator to work with user-defined types (like objects) by overloading plus() function.
Recommended Reading: Kotlin Operator Overloading
Here's a table of arithmetic operators and their corresponding functions:
| Expression | Function name | Translates to |
|---|---|---|
| a + b | plus | a.plus(b) |
| a - b | minus | a.minus(b) |
| a * b | times | a.times(b) |
| a / b | div | a.div(b) |
| a % b | mod | a.mod(b) |
No comments:
Post a Comment