VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/kotlin-plus-and-minus-operators/

⇱ Kotlin | Plus and minus Operators - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kotlin | Plus and minus Operators

Last Updated : 10 May, 2025

In Kotlin, working with collections like lists, sets, and maps is made easier and more readable thanks to operators like + (plus) and – (minus). These operators help you combine or remove elements from collections in a very natural way, just like doing math, but with objects instead of numbers.

Working With Lists

The + (Plus) Operator

The + operator is used when you want to add elements to a collection. It doesn’t change the original collection. Instead, it returns a new read-only collection that contains all the elements from the first collection plus the elements from the second collection. You can add a single item or an entire collection using +.

Syntax:

val result = list1 + list2

Example:


Output:

[three, one, twenty, zero]


The - (Minus) Operator

The operator is used when you want to remove elements from a collection. Like +, it doesn't modify the original collection, it returns a new one with elements removed. You can remove a single element, a group of elements, and even another collection

Example:

Output:

[one, twenty]


Working with Maps

The + (Plus) Operator

These operators behave slightly differently when you use them with maps. You can add a single key-value Pair and an another map. The result is a new map that combines all the entries from both. If the same key appears in both maps, the value from the right-hand side will replace the one on the left.

Example:


Output:

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


The - (Minus) Operator

When you use – with maps, it removes entries by their keys. You can remove one key or a group of keys.

Example:


Output:

{two=2, three=3}

Note: Both + and – always return a new collection. They do not change the original collection. If you want to modify a mutable collection, you’ll need to use functions like add() or remove() directly on that collection.

Comment
Article Tags:
Article Tags:

Explore