Kotlin basics

if expression in Kotlin

fun main(args: Array) {
    if (args.size < 2) {
        println("Please provide two numbers!")
        return
    }
    println("Max: " + max(args[0].toInt(), args[1].toInt()))
}

fun max(a: Int, b: Int) = if (a > b) a else b

Null check in Kotlin

// Return null if str does not hold a number
fun parseInt(str: String): Int? {
    try {
        return str.toInt()
    } catch (e: NumberFormatException) {
        println("One of the arguments isn't Int")
    }
    return null
}

fun main(args: Array) {
    if (args.size < 2) {
        println("Please supply 2 numbers!");
    } else {
        val x = parseInt(args[0])
        val y = parseInt(args[1])

        // We cannot say 'x * y' now because they may hold nulls
        if (x != null && y != null) {
            println("The product: " + (x * y))
        } else {
            println("One of the arguments is null")
    }
    }
}

is instance check and cast in Kotlin

fun main(args: Array) {
    println(getStringLength("aaa"))
    println(getStringLength(1))
}

fun getStringLength(obj: Any): Int? {
    if (obj is String)
        return obj.length // no cast to String is needed
    return null
}

while loop in Kotlin

fun main(args: Array) {
	if (args.size == 0) println("Please provide a number.");
    var i = 0
    while (i < args[0].toInt()) {
        println(i)
        i++    
    }
}

for loop in Kotlin

fun main(args: Array) {
    val arr = arrayOf("One", "Two", 3);

    for (item in arr) {
        println(item);
    }

    println("-------------------")

    for (i in arr.indices)
        println(arr[i])

    println("-------------------")

	for (i in 1..4) print(i) // prints "1234"
	println()
}

when in Kotlin is like a switch

fun main(args: Array) {
    cases("Hello")
    cases(1)
    cases(0L)
    cases(MyClass())
    cases("hello")
}

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

class MyClass() {
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search