https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Ayfri

08/25/2022, 3:49 AM
Hey, how would you name a
typealias <T>
for
Pair<T, T>
?
d

David Rawson

08/25/2022, 5:06 AM
What use cases did you have in mind for this typealias?
a

Ayfri

08/25/2022, 5:12 AM
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

Joffrey

08/25/2022, 6:54 AM
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

Youssef Shoaib [MOD]

08/25/2022, 6:54 AM
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

Ayfri

08/25/2022, 7:02 AM
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

Joffrey

08/25/2022, 7:12 AM
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

Klitos Kyriacou

08/25/2022, 8:31 AM
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

Ayfri

08/25/2022, 7:20 PM
Ah, is it also the case on K/JS ? It's for a web project
y

Youssef Shoaib [MOD]

08/25/2022, 7:29 PM
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
)
15 Views