joshua-r2
10/31/2017 - 2:15 PM

Arrays

This goes over the use of Arrays in Kotlin. The most common case is calling a Java method that takes an array or a Kotlin method with a vararg parameter. See the examples below for some of the capabilities of arrays on Kotlin.

fun main(args: Array<String>){

    //2 ways to initialize Arrays
    //One is the arrayOf() method
    val sesameStreetNumbers = arrayOf(1,2,3)

    //The other is to specify the number of indicies followed by a lambda which iterates the values
    val readTheAlphabet= Array(16){i->('a' + i).toString()}


    //Individual elements of the array can be set
    sesameStreetNumbers[2] = 42
    println("New number is ${sesameStreetNumbers[2]}")

    //Use forEachIndexed to perform a lambda on each element of the Array
    sesameStreetNumbers.forEachIndexed{someIndex,contents-> println("${contents} times two = ${contents*2}")}

    //We can use the .indices property to iterate through an array. This will print our ABCs
    for (i in readTheAlphabet.indices)
    {
        println("Letter number ${i}  in the alphabet is ${readTheAlphabet[i]}")
    }

    //For Java primitive types, the special class of array must be called for given types. This comes in handy when dealing
    //with Java libraries since Kotlin does not have a concept of primitive types
    val fiveZeros = IntArray(5)
    val twofalses = BooleanArray(2)
    val threechars = CharArray(3)
    val fourBytes = ByteArray(4)

    println(twofalses[0])
    println(threechars[0])
    println(fourBytes[0])

    //For the 4 examples above, we can also use typeArrayOf() to initialize
    val mixedBag = booleanArrayOf(true, false, false)


    //This example shows how to use the *(spread) operator to refer to a collection as a an array
    val someStrings = listOf("maybe", "I", "can")

    println("%s/%s/%s".format(*someStrings.toTypedArray()))

}