Kotlin Addition Operator
Kotlin Addition Operator returns the sum of given left operand and right operand.
Syntax
The syntax to use Arithmetic Addition operator is
n1 + n2
where
n1
is the left operand+
is the symbol used for Addition operatorn2
is the right operand
Return Value
The above expression returns the sum of the two given values. The data type of the return value depends on the given values. If given values are of different data types, then the resulting would be the higher data type (data type that can allocate larger memory).
Chaining Addition Operator
We can also chain the operator to add more than two numbers in a single expression, as shown in the following.
n1 + n2 + n3 + n4
You can add as many numbers in a single expression as you would like by chaining the Addition operator.
Examples
Addition of 4 and 6
In the following program, we take two variables: n1
, and n2
with the values 4
and 6
respectively; and find their sum.
Kotlin Program
fun main() {
var n1 = 4
var n2 = 6
val result = n1 + n2
println("n1 = $n1\nn2 = $n2\nn1 + n2 = $result")
}
Output
n1 = 4
n2 = 6
n1 + n2 = 10
Addition of more than two numbers in a single expression
In the following program, we take four integer variables: n1
, n2
, n3
, and n4
, and find the sum of the integer values in them.
Kotlin Program
fun main() {
var n1 = 4
var n2 = 6
var n3 = -2
var n4 = 7
val result = n1 + n2 + n3 + n4
println("n1 + n2 + n3 + n4 = $result")
}
Output
n1 + n2 + n3 + n4 = 15
Addition of 3.14 and 2.1
In the following program, we find the sum of floating point numbers.
Kotlin Program
fun main() {
var n1 = 3.14
var n2 = 2.1
val result = n1 + n2
println("n1 = $n1\nn2 = $n2\nn1 + n2 = $result")
}
Output
n1 = 3.14
n2 = 2.1
n1 + n2 = 5.24