Kotlin hello world

A simple print statement in Kotlin

// compile and run
// kotlinc hello.kt -include-runtime -d hello.jar
// java -jar hello.jar
fun main(args: Array) {
	println("Hello World!")
}

Reading command line arguments in Kotlin

// compile and run
// kotlinc command_line_args.kt -include-runtime -d hello.jar
// java -jar hello.jar Apple
fun main(args: Array) {
    if (args.size == 0) {
        println("There is no command line arguments provided!")
        return
    }
    println("Hello, ${args[0]}!")
}

for loop in Kotlin

// compile and run
// kotlinc array.kt -include-runtime -d hello.jar
// java -jar hello.jar Apple Banana
fun main(args: Array) {
    for (name in args)
        println("Hello, $name!")
}

switch in Kotlin

// compile and run
// kotlinc switch.kt -include-runtime -d hello.jar
// java -jar hello.jar FR
fun main(args: Array) {
    val language = if (args.size == 0) "EN" else args[0]
    println(when (language) {
        "EN" -> "Hello!"
        "FR" -> "Salut!"
        "IT" -> "Ciao!"
        else -> "Sorry, I can't greet you in $language yet"
    })
}

A simple hello class in Kotlin

// compile and run
// kotlinc class.kt -include-runtime -d hello.jar
// java -jar hello.jar Apple

class Greeter(val name: String) {
    fun greet() {
        println("Hello, ${name}");
    }
}

fun main(args: Array) {
    Greeter(args[0]).greet()
}

References:
http://kotlinlang.org/docs/reference/basic-types.html#strings
http://kotlinlang.org/docs/reference/basic-types.html#arrays
http://kotlinlang.org/docs/reference/basic-syntax.html#using-a-for-loop
http://kotlinlang.org/docs/reference/control-flow.html#when-expression
http://kotlinlang.org/docs/reference/classes.html#classes

Search within Codexpedia

Custom Search

Search the entire web

Custom Search