Kotlin Syntax
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 withvaland switch tovaronly when mutation is genuinely required. - Note
valvs. deep immutability:valprevents reassigning the reference, not mutating a mutable object it points to (such as aMutableList). - Package directories: Kotlin does not strictly require folder paths to match
packagenames, but matching them is standard practice on JVM projects.
Practice
Experiment with declarations and expressions in a small Main.kt file:
- Write a
mainfunction that declares twovalbindings and prints a formatted summary with a string template. - Rewrite an
if / elseblock that assigns avarinto an expression that initializes avaldirectly. - Add a single-expression helper function using
=and call it frommain.