Wednesday, 7 February 2018

Kotlin Android Syntax ( for, while, range, when)



Using a for loop

val items = listOf("apple", "banana", "kiwi")
for (item in items)
{
    println(item)
}

or

val items = listOf("apple", "banana", "kiwi")
for (index in items.indices)
{
    println("item at $index is ${items[index]}")
}


Using a while loop

val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size)
{
    println("item at $index is ${items[index]}")
    index++
}


Using when expression

fun describe(obj: Any): String =
when (obj)
{
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    else       -> "Unknown"
}


Using ranges

Check if a number is within a range using in operator:
val x = 10
val y = 9
if (x in 1..y+1)
{
    println("fits in range")
}


Check if a number is out of range:
val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex)
{
    println("-1 is out of range")
}

if (list.size !in list.indices)
{
    println("list size is out of valid list indices range too")
}


Iterating over a range:
for (x in 1..5)
{
    print(x)
}


or over a progression:
for (x in 1..10 step 2)
{
    print(x)
}
println()
for (x in 9 downTo 0 step 3)
{
    print(x)
}

Hello Reader
You can comment if any confusion in syntax or if need more explanation we'll reply you ASAP.
Thank you Safe & Happy Coding. :)
 

No comments:

Post a Comment

Kotlin Android Syntax (Collections, Class, Instance)

Using collections Iterating over a collection: for (item in items) {     println(item) } Checking if a collection con...