Hi ,
In previous post , I explained about default and named parameters of function is Kotlin.
Now in this post let's take a look how array will work in Kotlin.
Output:
That's it . Many more different cases are there which should be practiced .
In previous post , I explained about default and named parameters of function is Kotlin.
Now in this post let's take a look how array will work in Kotlin.
- Kotlin array , can be combination of values of same data types like Int, String etc.
- set & get is used for doing modifications and access the elements in array.
- Kotlin array are mutable in nature , so we can modify the elements.
- arrayOf<T> & intArrayOf is used to declare the arrays
Declaration of Arrays :
var myArray1 = arrayOf(3,7,9,23,65) var myArray2 = arrayOf<Int>(1,2,3,4,5) var myArray3 = arrayOf("A" , "B" , "C", "D", "E") var myArray4 = arrayOf<String>("a" , "b" , "c", "d","e") var myArray5= arrayOf(1,10,4, "Java","Android") //using intArrayOf var myArray6 : IntArray = intArrayOf(10,20,30,40,50)
Set the value of element:
myArray1.set(2, 10) myArray1[1] = 4 for(i in myArray1){ Log.d(TAG, ""+ i) }
Output:
3
4
10
23
65
-----------------------------------------------------------------
Let's take a look how we can modify the array and print the elements with one example :
-----------------------------------------------------------------
Let's take a look how we can modify the array and print the elements with one example :
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Mutable (can change) and fixed sized var myArray = Array<Int>(5) {0} /* index : 0 1 2 3 4 element: 0 0 0 0 0 */ myArray[4] = 45 myArray[2] = 3 myArray[0] = 21 /* index : 0 1 2 3 4 element: 21 0 3 0 45 */ // to print all the elements in array for (element in myArray){ println(element) } }
That's it . Many more different cases are there which should be practiced .