How to use plus and minus operators in Kotlin

Published by admin on

Kotlin plus and minus operators

Plus and minus operators with Kotlin list :

In kotlin, we can use the + and operators to add or subtract multiple collections. The first operand is a collection and the second operand is a collection or an element. It returns one new collection.

 

+ operator example :

+ is used for adding elements of more than one collection. You can add one new collection or only elements :

fun main(args: Array<string>) {
    val firstList = listOf(1,2,3);
    val secondList = listOf(6,7,8,9,10);

    val thirdList = firstList + 4 + 5 + secondList;

    println(thirdList);
}

It will print :

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Kotlin plus operator example

 

– operator example :

is used for subtraction :

fun main(args: Array<string>) {
    val firstList = listOf(1,2,3,4,5,6,7,8,9);
    val secondList = firstList - 4 - listOf(5,6,7,8,9);

    println(secondList);
}

It will print :

[1, 2, 3]

Kotlin minus operator example

 

+= and -= :

+= and -= assigns the value to the same collection :

a += b means a = a+b
a -= b means a = a-b

We need to use var collections as they modify the collection.

fun main(args: Array<string>) {
    var firstList = listOf(1,2,3);
    firstList += listOf(4,5,6);

    println(firstList);
}

It will print :

[1, 2, 3, 4, 5, 6]
Categories: kotlin

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *