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?
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.
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.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With