Although we should prefer working with collections over arrays, Kotlin makes it easy for you to work with them. In this video, learn various options for creating arrays of objects and primitives with Kotlin.
- [Instructor] Arrays in Kotlin are classes with a type parameter. In this example, we have an arrayOf ints, initialized with the values one, two, and three. Now if we wanted to do the same thing in Java just as a comparison, we'd define it this way with the type followed by brackets and then the name. In fact, these two things are comparable because the default array class creates boxed representations of the types. We just saw one way to initialize an array in Kotlin with the arrayOf function.
But you can also use the array function with your desired size of the array as well as a lambda which can initialize each element. In this example, we're creating an array of strings with the size of two and then setting each value to an empty string. You can also use the arrayOfNulls function if you want to create an array of a particular size with null elements. In this case, we created an array of strings with two null values, then set the first one to another string.
So if we print them out, we're going to get Heather and then null. Kotlin also allows you to create arrays of primitive types, but you have to use specialized classes for that. So in this example, we're creating an array of primitive Ints using the IntArrayOf function. This is going to return an int array. It's the same thing as using this syntax in Java where the have the lowercase int followed by the brackets. And these special classes are available for all of Java primitive types such as ints, chars, and Booleans as displayed here.
When coding in Kotlin, you're often working with collections. So it's useful to have a way to convert them to arrays in certain circumstances. And that's what the toTypedArray function does for us. In this example, we have our list of ints and we can get them as an array of ints by using the toTypedArray function. This is especially handy when we need to work with a vararg parameter. For example, the doInBackground method of AsyncTask takes in a vararg parameter.
And by simply placing the spread operator in front of our call to the toTypedArray function, we can get our list of flavors in the format that we need. Although we should prefer working with collections over arrays, it's nice that Kotlin makes it easy for us to work with them.
- What Kotlin has to offer
- Working with lambdas
- Common Android extension functions
- Kotlin Android Extensions overview
- Making use of the Anko library
- Working with coroutines
- Nullability and collections