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
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
You can try this:
var a = Array<Int>(5){0}
In this way, you can initialize the int array in koltin.
val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)
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)
}
Simple Way:
For Integer:
var number = arrayOf< Int> (10 , 20 , 30 , 40 ,50)
Hold All data types
var number = arrayOf(10 , "string value" , 10.5)
Here's an example:
fun main(args: Array<String>) {
val arr = arrayOf(1, 2, 3);
for (item in arr) {
println(item);
}
}
You can also use a playground to test language features.