Kotlin Syntax
In the previous chapters you ran a tiny program. Let's look at it word by word, then cover the basic rules every Kotlin file follows.
fun main() {
println("Learning Kotlin syntax")
}Learning Kotlin syntax
| Part | Meaning |
|---|---|
fun |
keyword that declares a function |
main |
the function's name; main is where the program starts |
() |
the parameter list — empty here |
{ ... } |
the function body |
println(...) |
a standard-library function that prints text and a line break |
"..." |
a string literal |
Statements and semicolons
Each line is usually one statement. A semicolon is only needed if you put two statements on the same line — and even then most Kotlin developers prefer separate lines.
fun main() {
println("one")
println("two"); println("three")
}one
two
three
Case sensitivity and naming
Kotlin is case-sensitive: println works, PrintLn does not exist. The naming conventions are:
| Thing | Convention | Example |
|---|---|---|
| functions, variables | camelCase | totalPrice, printReport() |
| classes, interfaces | PascalCase | ShoppingCart |
| constants | SCREAMING_SNAKE_CASE | MAX_ITEMS |
| packages | lowercase | com.example.shop |
Misspell a name and the compiler stops with an error. Errors are reported as File.kt:line:column:
fun main() {
Println("Hi")
}File.kt:2:5: error: Unresolved reference 'Println'.
Top-level declarations
Unlike Java, a Kotlin file may contain functions, variables and classes at the top level — not wrapped in anything. Their order in the file doesn't matter.
val greeting = "Welcome"
fun main() {
println(greeting)
showFooter()
}
fun showFooter() {
println("-- end --")
}Welcome
-- end --
main with arguments
Older code (and some tools) use main with a parameter that receives the command-line arguments as an array of strings. Both forms are valid entry points; use the parameter only when your program actually reads arguments.
fun main(args: Array<String>) {
println("main can also receive arguments")
println("Their type is Array<String>")
}main can also receive arguments
Their type is Array<String>
Packages and imports
Real projects start a file with a package line and import lines for code from other packages. Many common functions (println, listOf, maxOf…) are imported automatically.
package com.example.shop
import kotlin.math.sqrt
fun main() {
println(sqrt(16.0))
}Tip: Curly braces mark blocks, but indentation is for humans only. Use four spaces per level — IntelliJ formats your code with Ctrl+Alt+L.
Test yourself
When do you need a semicolon in Kotlin?
- At the end of every statement
- Only to separate two statements on the same line
- After every function
- Never; it is a syntax error
Which keyword declares a function?
- function
- def
- fun
- func
Can functions be declared outside of any class in Kotlin?
- Yes, top-level functions are allowed
- No, everything must be in a class
- Only
main - Only in scripts