Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't the entries in a Kotlin Pair mutable?

Tags:

kotlin

I have a MutableList of Pairs and I'd like to decrement the value of the first entry so my condition my pass(change):

while(n > 0) {
    if(sibice[i].first > 0) {
        sum += sibice[i].second
        //sibice[i].first-- will not compile
        n--
    } else i++
}

But the Pair class doesn't let me do that, besides creating my own pair is there any other workaround and why is this even the case?

like image 857
мајдејсаремех Avatar asked Oct 29 '17 16:10

мајдејсаремех


People also ask

Are pairs mutable?

A mutable pair consists of two object elements. MutablePair is defined in the Apache Commons Lang. The package has to be added to the classpath before MutablePair is used. If Maven is used, add the following in the dependencies section of pom.

Are lists mutable in Kotlin?

Kotlin mutableListOf()MutableList class is used to create mutable lists in which the elements can be added or removed. The method mutableListOf() returns an instance of MutableList Interface and takes the array of a particular type or mixed (depends on the type of MutableList instance) elements or it can be null also.

How do you update pair values?

The setAtX() method is used to set the Pair value in JavaTuples and a copy with a new value at the specified index i.e. index x. import org. javatuples.

How do you assign a value to pair in Kotlin?

In Kotlin, constructor is a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. To create a new instance of the Pair we use: Pair(first: A, second: B)


1 Answers

Like with all entities, issues arise with mutability.

In your case you can just update the list-entry with a new pair of values.

val newPair = oldPair.copy(first = oldPair.first-1)

Or directly use an array of length 2 instead intArrayOf(0, 0). So you can access the elements directly.

while(n > 0) {
    if(sibice[i][0] > 0) {
        sum += sibice[i][1]
        sibice[i][0]--
        n--
    } else i++
}

You could even define extension values first and second to the IntArray type and use it the same like before.

val IntArray.second get() = get(1)
var IntArray.first
    set(value) = set(0, value)
    get() = get(0)
like image 180
tynn Avatar answered Sep 19 '22 09:09

tynn