Kotlin Basic Syntax

The starting point

Like other programming languages, Kotlin needs a starting method. This method will be the first thing to be run when the program is executed. This method is called main.

fun main() {
    println("Hello world from Kotlin Code!")
}

Here you can see already some specific points about the programming language. A function is declared with the keyword fun. The return type must not be specified if it is void. The scope of a function is within curly brackets. You don’t need to end lines with semicolons. String literals are within characters.

Read more about Functions.

Package definitions and imports

Package specification should be at the top of the source file. It is not required to match directories and packages: source files can be placed arbitrarily in the file system.

package my.kotlin.demo

import kotlin.text.*

// ...

Variables

Kotlin differentiates between constant (val) and non-constant (var) variables. Each variable need to have a name and can be freely chosen by the programmer. The variable type is choosen by default by Kotlin. If necessary the type can be explicetly assigned.

var constantValue = 1
val variableValue = 2

var constantInt : Int = 1
val variableInt : Int = 2

Comments

Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments. Block comments in Kotlin can be nested.

// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */

/* The comment starts here
/* contains a nested comment */     
and ends here. */