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>) {
val firstcollection = listOf( "three" , "one" , "twenty" )
val plusList = firstcollection + "zero"
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>) {
val firstMap = mapOf( "one" to 1 , "two" to 2 , "three" to 3 )
print( "Result of plus operator: " )
println(firstMap + Pair( "four" , 4 ))
print( "Result of minus operator: " )
println(firstMap - "one" )
}
|
Output:
{one=1, two=2, three=3, four=4}
{two=2, three=3}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Sep, 2019
Like Article
Save Article
Vote for difficulty