https://kotlinlang.org logo
Title
s

stefano.maffullo

11/25/2017, 3:19 PM
Hello everyone, how can I create a data structure for example with two different types like ArrayList<Double, String>
j

jamie-purchase

11/25/2017, 3:22 PM
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

karelpeeters

11/25/2017, 3:25 PM
You can also take a look at
Either
from either #funktionale or #kategory.
c

cedric

11/25/2017, 3:31 PM
@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

stefano.maffullo

11/25/2017, 3:37 PM
Yeah it's fine for me to create my own structure, so my own "structure" it's a Class/Object?
c

cedric

11/25/2017, 3:38 PM
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

stefano.maffullo

11/25/2017, 3:48 PM
Thank you very much! Can I bother with another question? Is better a list of MyStructure or a 2D array?
c

cedric

11/25/2017, 3:52 PM
As a general rule, avoid using arrays. So
ArrayList
.
e.g.
listOf()
or
mutableListOf()
s

stefano.maffullo

11/25/2017, 4:01 PM
So I'll use listOf<MyClass>
👍 1
j

jamie-purchase

11/25/2017, 4:39 PM
@cedric can I ask why you would suggest avoiding arrays?
c

cedric

11/25/2017, 4:49 PM
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