SyntaxIntroduction to KotlinRunning Kotlin

Running Kotlin

Like Python, Kotlin can be executed interactively, directly from the command line. To execute Kotlin interactively, call ktc from the command line. You can then type commands interactively, and they will be executed immediately:

Welcome to Kotlin version 1.0.1-2 (JRE 1.7.0_95-b00)
Type :help for help, :quit for quit
>>> println("Hello World")
Hello World
>>> println("This is fun")
This is fun
>>> 
This is a good way to get to know a new programming language and to experiment with different types of data.

In most cases, however, you will want to write a script, consisting of Kotlin functions and statements to be executed. For example, we can create a file for1.kts with the following contents:

fun square(n : Int) {
  println("$n\t: ${n * n}")
}

for (i in 1 .. 10)
  square(i)
We can run this script from the command line with the command kts for1.kts:
$ kts for1.kts 
1	: 1
2	: 4
3	: 9
4	: 16
5	: 25
6	: 36
7	: 49
8	: 64
9	: 81
10	: 100

We will see soon that there is a third way to execute Kotlin code, namely to create one or more files that are compiled using the Kotlin compiler. A compiled programs starts much faster, can consist of multiple source files, and can contain your own class definitions.

But for the moment we will stick to Kotlin scripts.

SyntaxIntroduction to KotlinRunning Kotlin