Explain it simply
Syntax, simply
Syntax is the grammar a computer understands. People forgive a misspelling in an ordinary sentence, but a compiler never does: the kind of quote, the spelling and the capital letters must all be exact.
The good news is that Kotlin's core syntax is small. A program starts at `fun main()` and runs the lines inside it from top to bottom. There are no semicolons to type and no wrapper class to write. This lesson looks at those basic parts one by one.
Problem → Why → Solution
The problem: a tiny typo and the compiler refuses
The first mistakes beginners meet are simple ones. The program below contains three: a string written with single quotes, `println` misspelled as `printn`, and `nam` written instead of `name` inside a template. Compiling the file reports all three in one run: `error: too many characters in a character literal.` on line 3, `error: unresolved reference 'printn'.` on line 4 and `error: unresolved reference 'nam'.` on line 5.
fun main() {
val name = "Aye"
println('Hello, World!')
printn("Hello again")
println("Hello, $nam")
}Why the compiler is this strict
Catching these at compile time is a gift: you get to fix them before any user sees them. The compiler also tells you the file, the line and the column, so finding the spot is easy. Do not be afraid of an error message; read its first line, because most of the answer is in there.
Core concept: the parts of a Kotlin program
Every program starts at the `main` function. `fun` is the keyword that declares a function, `main` is its name, `()` is the parameter list (empty here) and `{ }` is the body. The form `fun main(args: Array<String>)` is also valid and receives the arguments passed on the command line. Both forms are correct, and neither needs the `public static void` and wrapper class that Java requires.
A statement ends where the line ends, so no semicolon is needed. A semicolon is only required to put two statements on one line, which you should not do. Indentation (four spaces by convention) is for human readers; the compiler only looks at the braces `{ }`, unlike Python.
`println(x)` prints x and then moves to a new line. `print(x)` does not move down, so the next output continues on the same line. Calling `println()` with no argument prints an empty line.
| Literal | Type | Notes |
|---|---|---|
| "Hello" | String | Double quotes, any length |
| 'H' | Char | Single quotes, exactly one character |
| """...""" | String | Raw string, may span lines, no escapes needed |
Special characters inside a string are written with a backslash: `\n` is a new line, `\t` a tab, `\"` a quote, `\\` a backslash and `\$` a dollar sign. `$name` inserts the value of the variable `name`, and inside `${ }` you can write a whole expression such as `${cups * price}`. Without braces only a plain name is taken, so `"$a * $b"` does not calculate anything.
The compiler ignores comments. `//` comments out the rest of a line and `/* ... */` comments out several lines; Kotlin even allows block comments inside block comments. `/** ... */` is a KDoc documentation comment, written before a function or class. One last rule: Kotlin is case-sensitive, so `main` and `Main`, or `println` and `Println`, are different names.
- Execution starts at main()
- Statements run top to bottom
- A statement ends at the line break
- Output goes to the console
The compiler will not skip even one wrong character, but it tells you exactly where the problem is.
General pattern: a program that prints
fun main() {
// a comment, ignored by the compiler
print("text that stays on the line")
println("text, then a line break")
println("a value: $name or ${expression}")
}The lines in the body run from top to bottom. `print` stays on the line and `println` moves down. Inside a string, `$name` and `${expression}` insert values. Everything after `//` is skipped by the compiler.
A program that prints a receipt
This one program contains every part of the lesson: both kinds of comment, `print` and `println`, a string template and the `\n` and `\"` escapes. Before running it, predict how many lines of output it produces; remember that each `\n` adds one.
// Prints a small receipt. Everything after // on a line is ignored.
fun main() {
/* A block comment can
span several lines. */
val shop = "Mingalar Cafe"
val cups = 3
val price = 1500
println("== $shop ==")
print("Cups: ")
println(cups)
println("Menu:\n tea\n coffee")
println("The sign says \"open\"")
println("Total: ${cups * price} MMK")
}Code breakdown
- A line comment
// Prints a small receipt. Everything after // on a line is ignored.The compiler does not read anything after `//`. It is a note for humans. The `/* ... */` block comment in this program works the same way, but across several lines.
- The entry point
fun main() {This is where the program starts. The lines inside these braces run from top to bottom. There is no semicolon at the end of this line.
- A template with a name
println("== $shop ==")`$shop` is replaced by the value of `shop`, Mingalar Cafe, and `println` then moves to a new line. The output is `== Mingalar Cafe ==`.
- print without a line break
print("Cups: ")`print` does not move down, so the following `println(cups)` writes `3` right after `Cups: ` and the line reads `Cups: 3`. You can pass a non-text value such as an Int straight to `println`.
- A newline escape
println("Menu:\n tea\n coffee")The two `\n` sequences insert new lines, so one `println` produces three lines. In the source file `\n` is typed as two characters, a backslash and an n, and Kotlin reads it as a line break.
- An escaped quote
println("The sign says \"open\"")To put a double quote inside a string, write `\"`. Without the backslash the compiler would think the string ends there. The output shows the quotes as `"open"`.
- An expression in a template
println("Total: ${cups * price} MMK")Because `cups * price` is inside `${ }`, Kotlin calculates 3 * 1500 = 4500 and inserts the result. Without the braces you would only get the characters `3 * 1500`.
== Mingalar Cafe ==
Cups: 3
Menu:
tea
coffee
The sign says "open"
Total: 4500 MMKHow to read a compiler error message
An error message has five parts: the file name, the line number, the column number, `error` (or `warning`) and the explanation. As below, the compiler also repeats the code line and points a `^` at the spot. When many errors appear, fix the first one first, because the later ones are often caused by it.
broken.kt:4:5: error: unresolved reference 'printn'.
printn("Hello again")
^^^^^^`broken.kt:4:5` means line 4, column 5 of `broken.kt`. `unresolved reference 'printn'` means no declaration named `printn` exists. When you see that message, check spelling, capitalization and a forgotten import first.
Raw strings and the dollar sign
For long text over several lines, use triple quotes `"""`. A raw string needs no escapes such as `\n`, and line breaks stay where you typed them. Calling `.trimIndent()` afterwards removes the indentation of the code so the text starts at the left edge. To put a real dollar sign in text, write `\$` (or `${'$'}`).
fun main() {
val poem = """
Roses are red,
Kotlin is concise.
""".trimIndent()
println(poem)
println("Price: \$5")
}In real projects
How syntax conventions work in real projects
The Kotlin community has an official style guide called the Kotlin coding conventions: four-space indentation, camelCase for functions and variables, opening braces at the end of the line. IntelliJ IDEA formats code automatically, and tools such as ktlint can fail a build on style violations. That is how a team's code reads as if one person wrote it.
In production code `println` is usually not used for logging; a logging library is, though command-line tools, scripts and exercises keep using `println`. String templates appear everywhere: log messages, error messages, labels. If you write a concatenation such as `"Hi " + name + "!"`, the IDE will often suggest replacing it with a template, which is easier to read and cannot forget a piece.
Common mistakes
Common mistakes
1. Writing a string with single quotes
`val greeting = 'Hello'` fails with `error: too many characters in a character literal.` Single quotes are for exactly one Char, so use double quotes: `"Hello"`. `'H'` on its own is fine.
2. Misspelling a name or getting its case wrong
`printn("Hi")` or `Println("Hi")` gives `error: unresolved reference`. Writing `Main` instead of `main` is sneakier: the file compiles, but there is no entry point, so `java -jar` says `no main manifest attribute, in hello.jar`.
3. Forgetting the braces in a template
`"Total: $cups * $price"` does not print 4500; it prints `Total: 3 * 1500`. `$` takes only a plain name, so a calculation has to go inside braces: `"${cups * price}"`.
4. Leaving a bracket or quote open
Forgetting the closing bracket in `println("Hello"` gives `error: syntax error: Expecting ')'.` The line it reports can be later than where you actually forgot it, so look at the previous line too.
Best practices
Best practices
- Keep indentation consistent at four spaces and let your editor's auto-format do it.
- Write one statement per line instead of chaining them with semicolons.
- Prefer string templates to string concatenation; they are shorter and easier to read.
- In comments, explain why the code does something rather than repeating what it does.
Mini challenge
Mini challenge: a business card
Print a business card for yourself on the console, drawn inside a box.
- Store a name, a job title and your years of experience in three `val`s
- Draw the top and bottom of the box with a line such as `+---+`
- Print the first content line with one `print` followed by one `println`
- Use one `${ }` expression to turn years into months, and add a motto line containing quotes written with `\"`
fun main() {
// TODO: vals for name, role and years of experience
// TODO: print the top border line
// TODO: print the name using print(...) and then println(...)
// TODO: print the role with a template, and the years as months with ${ }
// TODO: print a motto that contains double quotes (escape them)
// TODO: print the bottom border line
}Expected: Your own name and job will differ, but the shape is, for example: +----------------------+ | Ma Hnin | Kotlin developer | 36 months of Kotlin | Motto: "Type it, run it." +----------------------+
Show hint
`print("| ")` followed by `println(name)` produces a single line. For a motto with quotes, escape them with backslashes as in `"| Motto: \"Type it, run it.\""`.
Show solution
fun main() {
// Business card printer
val name = "Ma Hnin"
val role = "Kotlin developer"
val years = 3
println("+----------------------+")
print("| ")
println(name)
println("| $role")
println("| ${years * 12} months of Kotlin")
println("| Motto: \"Type it, run it.\"")
println("+----------------------+")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A program starts at `fun main()` and runs statements from top to bottom with no semicolons.
- `print` stays on the line and `println` moves down; comments use `//` and `/* */`.
- Strings use double quotes and Chars use single quotes; escapes are `\n` and `\"`; templates are `$name` and `${expr}`.
- Read the file:line:column and first line of an error message, and remember Kotlin is case-sensitive.
Kotlin releases — Kotlin