Ayfri
08/25/2022, 3:49 AMtypealias <T>
for Pair<T, T>
?David Rawson
08/25/2022, 5:06 AMAyfri
08/25/2022, 5:12 AMJoffrey
08/25/2022, 6:54 AMdata class NumberRun(val value: Int, val length: Int)
Youssef Shoaib [MOD]
08/25/2022, 6:54 AMIntRepetition
or just Repetiton<T> = Pair<T, Int>
Ayfri
08/25/2022, 7:02 AMCouple<T>
= Pair<T, T>
, but yes maybe I should use a class, it's just that it's simple to use the to
infix function 🙂Joffrey
08/25/2022, 7:12 AMto
is far shadowed by the inconvenience of using first
and second
to get the components instead of nice meaningful names. This is especially true when you're not the one who wrote the code, or you come back to a piece of code after some timeKlitos Kyriacou
08/25/2022, 8:31 AMPair<Int, Int>
would that be stored in memory as two references? On the other hand, a non-generic custom class would store them as values.Ayfri
08/25/2022, 7:20 PMYoussef Shoaib [MOD]
08/25/2022, 7:29 PMinfix fun repeat
that can be used like 42 repeat 4
instead of using to
. Btw, a basic skeleton of such an algorithm would be like this:
buildList<NumberRun> {
var lastNumber = 0
var repetitions = 0
for (number in originalList) {
if (number == lastNumber)
repetitions++
else {
if (repetitions > 0) add(lastNumber repeat repetitions)
lastNumber = number
repetitions = 1
}
}
if (repetitions > 0) add(lastNumber repeat repetitions)
}
In Kotlin in general most developers don't shy away from defining a lot of data classes because of just how simple defining them is. There tends to be a reliance on classes to provide "documentation" in a way through property names for instance (e.g. first
is less descriptive than length
)