In Java an array can be initialized such as:
int numbers[] = new int[] {10, 20, 30, 40, 50}
How does Kotlin\'s array initialization look li
In my case I need to initialise my drawer items. I fill data by below code.
val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)
// Use lambda function to add data in my custom model class i.e. DrawerItem
val drawerItems = Array<DrawerItem>(iconsArr.size, init =
{ index -> DrawerItem(iconsArr[index], names[index])})
Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)
Custom Model class-
class DrawerItem(var icon: Int, var name: String) {
}
In Kotlin we can create array using arrayOf()
, intArrayOf()
, charArrayOf()
, booleanArrayOf()
, longArrayOf()
functions.
For example:
var Arr1 = arrayOf(1,10,4,6,15)
var Arr2 = arrayOf<Int>(1,10,4,6,15)
var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot")
var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh")
var Arr5: IntArray = intArrayOf(5,10,15,20)
you can use this methods
var numbers=Array<Int>(size,init)
var numbers=IntArray(size,init)
var numbers= intArrayOf(1,2,3)
example
var numbers = Array<Int>(5, { i -> 0 })
init represents the default value ( initialize )
I'm wondering why nobody just gave the most simple of answers:
val array: Array<Int> = [1, 2, 3]
As per one of the comments to my original answer, I realized this only works when used in annotations arguments (which was really unexpected for me).
Looks like Kotlin doesn't allow to create array literals outside annotations.
For instance, look at this code using @Option from args4j library:
@Option( name = "-h", aliases = ["--help", "-?"], usage = "Show this help" ) var help: Boolean = false
The option argument "aliases" is of type Array<String>
I think one thing that is worth mentioning and isn't intuitive enough from the documentation is that, when you use a factory function to create an array and you specify it's size, the array is initialized with values that are equal to their index values. For example, in an array such as this:
val array = Array(5, { i -> i })
, the initial values assigned are [0,1,2,3,4]
and not say, [0,0,0,0,0]
. That is why from the documentation, val asc = Array(5, { i -> (i * i).toString() })
produces an answer of ["0", "1", "4", "9", "16"]
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
See Kotlin - Basic Types for details.
You can also provide an initializer function as a second parameter:
val numbers = IntArray(5) { 10 * (it + 1) }
// [10, 20, 30, 40, 50]