Hello everyone, how can I create a data structure ...
# announcements
s
Hello everyone, how can I create a data structure for example with two different types like ArrayList<Double, String>
j
this is likely a naive solution but in Java you could say
ArrayList<Object>
and cast them in and out... or create a class that has a property of either Double or String and have an
ArrayList<MyClass>
but as for Kotlin likely far better ways
to clarify: one value per element of type Double or String right? if it's a double and string per element then use
ArrayList<Pair...
k
You can also take a look at
Either
from either #funktionale or #kategory.
c
@stefano.maffullo Short answer is you can't in Kotlin, but a language like Ceylon can. In Kotlin, you'd create your own structure that contains all the types you need and discriminate on them (e.g.
Either
)
s
Yeah it's fine for me to create my own structure, so my own "structure" it's a Class/Object?
c
For example
data class MyStructure { val d: Double, val s: String }
and put that in your list
🤓 1
Might want to make it a bit more sophisticated so you don't need to type check to know which field is present/absent
s
Thank you very much! Can I bother with another question? Is better a list of MyStructure or a 2D array?
c
As a general rule, avoid using arrays. So
ArrayList
.
e.g.
listOf()
or
mutableListOf()
s
So I'll use listOf<MyClass>
👍 1
j
@cedric can I ask why you would suggest avoiding arrays?
c
The general reason is that arrays don't play nicely with generics, mostly because they predate them. This was already a rule of thumb in Java so it's not specific to Kotlin
👍 1