Kotlin | Plus and minus Operators

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 –



filter_none

edit
close

play_arrow

link
brightness_4
code

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)
}

chevron_right


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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

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")
}

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.