How to initialize an array in Kotlin with values?

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

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 like?

回答1:

You can:

val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50) 

See Kotlin - Basic Types for details.



回答2:

Here's an example:

fun main(args: Array) {     val arr = arrayOf(1, 2, 3);     for (item in arr) {         println(item);     } } 

You can also use a playground to test language features.



回答3:

Worth to mention that when using kotlin builtines (e.g. intArrayOf(), longArrayOf(), arrayOf(), etc) you are not able to initialize the array with default values (or all values to desired value) for a given size, instead you need to do initialize via calling according class constructor.

// Array of integers of a size of N val arr = IntArray(N)  // Array of integers of a size of N initialized with a default value of 2 val arr = IntArray(N, {i -> 2}) 


回答4:

In Kotlin There are Several Ways.

var arr = IntArray(size) // construct with only size 

Then simply initial value from users or from another collection or wherever you want.

var arr = IntArray(size, { 0 } ) // construct with size and fill array with 0 var arr = IntArray(size, { it * 1 } ) // construct with size and fill with its index 

We also can create array with built in function like-

var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values 

Another way

var arr = Array(size, { 0 } ) // it will create an integer array var arr = Array(size, { "$it" } ) // this will create array with "0", "1", "2" and so on. 

You also can use doubleArrayOf() or DoubleArray() or any primitive type instead of Int.



回答5:

you can use this methods

var numbers=Array(size,init) var numbers=IntArray(size,init) var numbers= intArrayOf(1,2,3) 

example

var numbers = Array(5, { i -> 0 }) 

init represents the default value ( initialize )



回答6:

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"]



回答7:

Old question, but if you'd like to use a range:

var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray() 

Yields nearly the same result as:

var numbers = Array(5, { i -> i*10 + 10 }) 

result: 10, 20, 30, 40, 50

I think the first option is a little more readable. Both work.



回答8:

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 = 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(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) {  } 


回答9:

You can try this:

var a = Array(5){0} 


回答10:

intialize array in this way : val paramValueList : Array = arrayOfNulls(5)



回答11:

You can create an Int Array like this:

val numbers = IntArray(5, { 10 * (it + 1) }) 

5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]

origin function is:

 /**  * An array of ints. When targeting the JVM, instances of this class are   * represented as `int[]`.  * @constructor Creates a new array of the specified [size], with all elements   *  initialized to zero.  */  public class IntArray(size: Int) {        /**         * Creates a new array of the specified [size], where each element is          * calculated by calling the specified         * [init] function. The [init] function returns an array element given          * its index.         */       public inline constructor(size: Int, init: (Int) -> Int)   ...  } 

IntArray class defined in the Arrays.kt



回答12:

Declare int array at global

var numbers= intArrayOf() 

next onCreate method initialize your array with value

override fun onCreate(savedInstanceState: Bundle?) {     super.onCreate(savedInstanceState)     setContentView(R.layout.activity_main)     //create your int array here     numbers= intArrayOf(10,20,30,40,50) } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!