Careeroza
Basic Syntax
Program Structure
Example
A Kotlin file can contain functions directly. fun declares a function, curly braces hold its body, and each statement usually sits on its own line.
fun main() {
println("Line one")
println("Line two"); println("Two statements on one line need a semicolon")
}Output
Line one Line two Two statements on one line need a semicolon
Syntax Rules
fun main()is the entry point.- Kotlin is case-sensitive:
printlnworks,PrintLndoes not. - Semicolons are optional at the end of a line.
- Blocks use
{ }; indentation is for readability only (4 spaces is the convention). - Strings use double quotes
"text"; a single character uses single quotes'A'. - File names end with
.kt(scripts use.kts).
Packages and Imports
Real projects put each file in a package and import what they need. Many common functions (println, listOf, maxOf) are imported automatically.
Example
Here we import sqrt and PI from the kotlin.math package.
import kotlin.math.PI
import kotlin.math.sqrt
fun main() {
println(sqrt(144.0))
println(PI)
}Output
12.0 3.141592653589793