Kotlin Syntax

Kotlin's syntax is designed to be clean and readable, starting with a single fun main() entry point and statements that don't need trailing semicolons.

The Structure of a Kotlin Program

Every standalone Kotlin program needs exactly one fun main() function, which is where execution begins. Code files use the .kt extension, and a single file can contain multiple functions, classes, and top-level variables, all of which are visible to main() as long as they're in the same file or imported from elsewhere.

The Simplest Kotlin Program

fun main() {
    println("Kotlin starts here")
}

Statements Don't Need Semicolons

Unlike Java, C, or JavaScript, Kotlin does not require a semicolon at the end of a statement. The compiler uses line breaks to determine where one statement ends and the next begins. You can still use a semicolon if you want to place two statements on the same line, but idiomatic Kotlin code almost never uses them.

Semicolons Are Optional

fun main() {
    val first = "Kotlin"
    val second = "is concise"
    println(first)
    println(second)
}
Note: A semicolon is only ever required when you deliberately put more than one statement on a single line, such as val x = 1; println(x).

Blocks, Braces, and Indentation

Curly braces { } define a block of code, such as the body of a function, a loop, or a conditional. Kotlin does not enforce indentation the way Python does, but consistent 4-space indentation is the community standard and is what most IDEs insert automatically.

  • Kotlin is case-sensitive, so myValue and MyValue are different identifiers
  • Function and variable names conventionally use camelCase, like calculateTotal
  • Class names conventionally use PascalCase, like CustomerAccount
  • Every .kt file compiles independently but can share code through imports

Functions and Conditionals Use Braces

fun describeNumber(n: Int): String {
    return if (n % 2 == 0) {
        "$n is even"
    } else {
        "$n is odd"
    }
}

fun main() {
    println(describeNumber(7))
}
Note: Kotlin is case-sensitive even for built-in functions - typing Println instead of println will fail to compile with an 'unresolved reference' error.

Exercise: Kotlin Syntax

Which keyword declares a function in Kotlin?