Kotlin Syntax
Understanding Kotlin's fundamental syntax rules
📝 Kotlin Syntax Basics
Kotlin syntax is clean, concise, and expressive. Learn the fundamental rules for writing Kotlin code including variables, functions, and basic program structure with practical examples.
// Basic Kotlin syntax example
fun main() {
val message = "Learning Kotlin syntax!"
println(message)
}
Output:
Basic Syntax Elements
Variables
val (immutable) and var (mutable)
val name = "John"
var age = 25
Functions
Declared with fun keyword
fun greet(name: String) {
println("Hello, $name!")
}
String Templates
Embed expressions in strings
val result = "2 + 3 = ${2 + 3}"
Type Inference
Automatic type detection
val number = 42 // Int
val text = "Hello" // String
🔹 Variables and Constants
Kotlin uses two keywords for declaring variables:
// Immutable (read-only) - preferred
val pi = 3.14159
val name = "Kotlin"
// Mutable (can be changed)
var counter = 0
var isActive = true
// Explicit type declaration
val age: Int = 25
var score: Double = 95.5
// Late initialization
lateinit var database: String
Example Usage:
// pi = 3.14 // ✗ Error (val is immutable)
🔹 Functions
Functions are declared using the
fun
keyword:
🔸 Basic Function Syntax
// Function with parameters and return type
fun add(a: Int, b: Int): Int {
return a + b
}
// Single expression function
fun multiply(a: Int, b: Int) = a * b
// Function with default parameters
fun greet(name: String, greeting: String = "Hello") {
println("$greeting, $name!")
}
// Function with no return value (Unit)
fun printInfo(message: String) {
println("Info: $message")
}
Usage:
val product = multiply(4, 6) // 24
greet("Alice") // Hello, Alice!
greet("Bob", "Hi") // Hi, Bob!
🔹 String Templates
Kotlin provides powerful string interpolation:
val name = "Kotlin"
val version = 1.8
// Simple variable interpolation
println("Language: $name")
// Expression interpolation
println("Version: $version")
println("Next version: ${version + 0.1}")
// Complex expressions
val numbers = listOf(1, 2, 3, 4, 5)
println("Sum: ${numbers.sum()}")
println("Average: ${numbers.average()}")
// Multiline strings
val poem = """
Roses are red,
Violets are blue,
Kotlin is awesome,
And so are you!
""".trimIndent()
Output:
Version: 1.8
Next version: 1.9
Sum: 15
Average: 3.0
🔹 Control Flow
Basic control structures in Kotlin:
🔸 If Expressions
val score = 85
// Traditional if statement
if (score >= 90) {
println("Excellent!")
} else if (score >= 70) {
println("Good job!")
} else {
println("Keep trying!")
}
// If as expression
val grade = if (score >= 90) "A"
else if (score >= 80) "B"
else if (score >= 70) "C"
else "F"
println("Grade: $grade")
🔸 When Expression
val day = 3
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6, 7 -> "Weekend"
else -> "Invalid day"
}
println("Day $day is $dayName")
Output:
Grade: B
Day 3 is Wednesday
🔹 Loops
Different ways to iterate in Kotlin:
// For loop with range
for (i in 1..5) {
print("$i ")
}
println()
// For loop with list
val fruits = listOf("apple", "banana", "orange")
for (fruit in fruits) {
println("I like $fruit")
}
// While loop
var count = 3
while (count > 0) {
println("Countdown: $count")
count--
}
// Repeat function
repeat(3) {
println("Kotlin is fun!")
}
Output:
I like apple
I like banana
I like orange
Countdown: 3
Countdown: 2
Countdown: 1
Kotlin is fun!
Kotlin is fun!
Kotlin is fun!