Kotlin Syntax

Kotlin syntax is compact and expression-oriented. The language prefers readability, explicit types when needed, and fewer special cases than older JVM languages.

Declarations

Kotlin separates read-only references (val) from reassignable variables (var). Preferring val by default prevents accidental state mutation and makes concurrent or refactored code easier to reason about. Semicolons are optional at the end of lines, and string templates ($name or ${expr}) embed values directly inside double-quoted strings:

val language = "Kotlin"       // read-only reference (cannot be reassigned)
var count = 1                 // mutable reference (reassignment allowed)
count += 1
println("$language count = $count, next = ${count + 1}")

Expressions

Unlike statement-heavy languages where if or try only control execution flow, most Kotlin constructs are expressions that evaluate to a value. Returning a value directly from if or when eliminates temporary uninitialized variables and guarantees every branch produces a result:

val score = 88
// `if` returns a value, so `grade` can remain an immutable `val`
val grade = if (score >= 90) "A" else if (score >= 80) "B" else "C"
println("Score $score -> Grade $grade")

Program shape

A Kotlin entry point is a top-level fun main() function—you do not need to wrap it in a boilerplate class. Package declarations and imports sit at the top of the file, and single-expression functions can use = instead of curly braces and an explicit return:

package demo

// Single-expression function: return type Int is inferred
fun double(x: Int) = x * 2

fun main(args: Array<String>) {
    val label = if (args.isNotEmpty()) args[0] else "Kotlin"
    println("Hello $label! double(5) = ${double(5)}")
}

Syntax rules

Keep these foundational conventions in mind as you write idiomatic Kotlin:

  • Default to val: Declare variables with val and switch to var only when mutation is genuinely required.
  • Note val vs. deep immutability: val prevents reassigning the reference, not mutating a mutable object it points to (such as a MutableList).
  • Package directories: Kotlin does not strictly require folder paths to match package names, but matching them is standard practice on JVM projects.

Practice

Experiment with declarations and expressions in a small Main.kt file:

  1. Write a main function that declares two val bindings and prints a formatted summary with a string template.
  2. Rewrite an if / else block that assigns a var into an expression that initializes a val directly.
  3. Add a single-expression helper function using = and call it from main.