Kotlin Syntax Basics
Prerequisites: How Kotlin code runs
A few rules cover most of what Kotlin code looks like.
One statement per line, no semicolons. A semicolon is only needed to put two statements on one line.
Curly braces mark blocks of code:
fun main() {
if (10 > 5) {
println("Ten is bigger")
}
}
Ten is bigger
Conditions go in parentheses: if (10 > 5).
Indentation is four spaces by convention. Kotlin doesn't require it, but it keeps code readable, and IntelliJ formats it for you (Code → Reformat Code).
Case matters. name and Name are different. The conventions:
camelCase for variables and functions (firstName,
calculateTotal); PascalCase for classes (ShoppingCart); and
SCREAMING_SNAKE_CASE for constants (MAX_USERS).
Almost everything is an expression. if, when, and try all
produce values you can assign — you'll see this throughout the course.
Common mistakes
- A missing closing brace — the compiler reports something like
Missing '}'. Your IDE highlights matching braces to help. - Putting a line break in the wrong place. Kotlin ends a statement at
a line break when it can, so start a continued line with an operator
like
.or?:— not end the previous line with+, which also works but is easy to get wrong.