Winny
Winny

Reputation: 131

Alternatives to array in Kotlin

at the moment I have a very simple array:

val name = arrayListOf(
"Steve", 
"David",
"Chris,
"Bev")



MyResult.text = name[2]

Giving “Chris”.

But I would like to use the same data but including the age with something like:

val name = array????(
0, "Steve", 20,
1, "David", 28,
2, "Chris, 28,
3, "Bev", 46)

MyResult.text = name[2,0]

Giving the same result, ie using something that allows me to specify the position in the array please to be able to return the item?

Any help appreciated!

Upvotes: 0

Views: 493

Answers (1)

gidds
gidds

Reputation: 18617

Arrays (and lists, which are more generally useful) are for when every element is the same type.

In this case, that's not true.  You have a mix of types, because you have internal structure: some elements relate directly to others, in a regular way.  What you have is effectively a list of people, each with several fields.  So code that!  It's very straightforward:

data class Person(val id: Int, val name: String, val age: Int)

val people = listOf(Person(0, "Steve", 20),
                    Person(1, "David", 28),
                    Person(2, "Chris", 28),
                    Person(3, "Bev", 46))

This way, the whole type system is working for you.  Because you've told the compiler what those fields represent and how they relate to each other, it can prevent you from mixing them up by mistake, and it knows what you can do with each one.  You can then manipulate them in all sorts of ways.  Not just getting the person at given position in the list:

val firstPerson = people[0]

But getting a person by name:

val david = people.find{ it.name == "David" }

Or finding the youngest person:

val youngest = people.minByOrNull{ it.age }

Or getting their names in alphabetical order:

val names = people.map{ it.name }.sorted()

Or many other things.  The Kotlin standard library has a lot of extension functions and other machinery for handling lists, and Kotlin's data classes make it very easy to create value objects like this.

If there's no inherent ordering between the people, then maybe a set would be a better fit.

Or if you often refer to them by ID, then you could store them in a map with their ID as the key.

It all depends what you're going to do with them.

But an array is unlikely to be the best option.  Arrays are a necessary evil, needed for a few specific things (varargs, implementing higher-level structures, storing primitive values efficiently, and interoperating with legacy code), but for most other uses lists are more powerful, more flexible, and better supported.  Most Kotlin code should use lists instead of arrays.

Upvotes: 2

Related Questions