Thursday, 30 November 2017

Kotlin: Arrays

Array represents a collection of elements of same type. Kotlin provides Array class to represent arrays.

By using the library function arrayOf, you can define an array.

Ex
val numbers: Array<Int> = arrayOf(10, 20, 30, 40, 50)

ArrayDemo.kt
fun main(args: Array<String>) {

 val numbers: Array<Int> = arrayOf(10, 20, 30, 40, 50)

 for (element in numbers) {
  println(element)
 }

}

Output
10
20
30
40
50

Kotlin provides below library functions to define array of primitive types.

byteArrayOf()
shortArrayOf()
intArrayOf()
longArrayOf()
floatArrayOf()
doubleArrayOf()
CharArray()
BooleanArray()


PrimitiveArrayDemo.kt
fun main(args: Array<String>) {

 var a: ByteArray = byteArrayOf(1, 2, 3)
 val b: ShortArray = shortArrayOf(1, 2, 3)
 val c: IntArray = intArrayOf(1, 2, 3)
 var d: LongArray = longArrayOf(1L, 2L, 3L)
 val e: FloatArray = floatArrayOf(1f, 2f, 3f)
 val f: DoubleArray = doubleArrayOf(1.1, 2.2, 3.3)
 var g: CharArray = charArrayOf('a', 'b', 'c')
 var h: BooleanArray = booleanArrayOf(true, false, true)

 println("Elements of Byte array are : ")
 for (ele in a) {
  println(ele)
 }

 println("\n\nElements of Short array are : ")
 for (ele in b) {
  println(ele)
 }

 println("\n\nElements of Int array are : ")
 for (ele in c) {
  println(ele)
 }

 println("\n\nElements of Long array are : ")
 for (ele in d) {
  println(ele)
 }

 println("\n\nElements of Float array are : ")
 for (ele in e) {
  println(ele)
 }

 println("\n\nElements of Double array are : ")
 for (ele in f) {
  println(ele)
 }

 println("\n\nElements of Char array are : ")
 for (ele in g) {
  println(ele)
 }

 println("\n\nElements of Boolean array are : ")
 for (ele in h) {
  println(ele)
 }

}


Output
Elements of Byte array are :
1
2
3


Elements of Short array are :
1
2
3


Elements of Int array are :
1
2
3


Elements of Long array are :
1
2
3


Elements of Float array are :
1.0
2.0
3.0


Elements of Double array are :
1.1
2.2
3.3


Elements of Char array are :
a
b
c


Elements of Boolean array are :
true
false
true


Previous                                                 Next                                                 Home

No comments:

Post a Comment