Hey, how would you name a `typealias <T>` fo...
# getting-started
a
Hey, how would you name a
typealias <T>
for
Pair<T, T>
?
d
What use cases did you have in mind for this typealias?
a
just to have a pair of Int, for storing a number and how many time it appears in a row, for optimising storage of a list of numbers
j
This is usually called a run , at least in algorithms like Run-Length encoding (which seems to be what you're doing here). But why use a typealias here? Why not actually name a data class for this?
Copy code
data class NumberRun(val value: Int, val length: Int)
👍 3
y
Do you really need a pair in this case? Because is every pair of Int really a valid member of that? I'd say make your own data class. Regardless though, data class or type alias, I'd name it
IntRepetition
or just
Repetiton<T> = Pair<T, Int>
👍 1
a
Okay good advices, thanks for the name of the algorith also, I'm struggling a bit for now as the implementation doesn't work 😕 For now I sticked with
Couple<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 🙂
j
The convenience of using
to
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 time
👍 1
k
I was just thinking about performance... if you use a
Pair<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.
1
a
Ah, is it also the case on K/JS ? It's for a web project
y
In that case I don't think? Because primitives aren't really a thing on JS. Still, I think that it's dubious at best. You could define an
infix 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:
Copy code
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
)