Open In App

Kotlin | Plus and minus Operators

Last Updated : 05 Sep, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

In Kotlin, plus and minus operators are used to work with the list of objects which is usually referred to as Collections (List, Set, Maps).

As the name suggests, plus operator adds up or concatenates the elements or objects of the given collections. The elements of the first collection remains as it is and the elements of second collection are added with them and the result is then returned in a new read-only collection.

Another one minus operator also contains all the elements of first collection but it removes the elements of second collection, if it is a single element, minus operator removes its occurrence. Just like plus operator result is stored in a new read-only collection.

Syntax:

val result = collection1 + collection2

Kotlin example demonstrates the use of plus and minus operator for a list of elements –




fun main(args: Array<String>) {
    // initialize collection with string elements
    val firstcollection = listOf("three", "one", "twenty")
  
    // perform plus operator on list
    val plusList = firstcollection + "zero"
    // perform minus operator on list
    val minusList = firstcollection - listOf("three")
    println("Result of plus operator is : " + plusList)
    println("Result of minus operator is : " + minusList)
}


Output:

Result of plus operator is : [three, one, twenty, zero]
Result of minus operator is : [one, twenty]

Plus and minus operators work slightly different on Maps than other collections. Plus operator returns a Map that contains elements from both Maps: a Map on the left and a Pair or another Map on the right.

Minus operator creates a Map from entries of a Map on the left except those with keys from the right-hand side operand.

Kotlin example demonstrates the use of both the operators on Maps –




fun main(args : Array<String>) {
    // create and initialize map with keys and values
    val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3)
    // plus operator to add 4
    print("Result of plus operator: ")
    println(firstMap + Pair("four", 4))
    // minus operator to minus 1
    print("Result of minus operator: ")
    println(firstMap - "one")
}


Output:

{one=1, two=2, three=3, four=4}
{two=2, three=3}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads