Kotlin Syntax: A Quick Tour
Kotlin’s syntax is designed to be concise, safe, and expressive. In this guide, we’ll explore the core syntax elements that make Kotlin a modern and powerful programming language.
Basic Structure
Package Declaration
package com.example.myapp
import java.util.*
Main Function
fun main() {
println("Hello, Kotlin!")
}
Variables and Constants
Variable Declaration
// Mutable variable
var count = 0
// Immutable variable (constant)
val PI = 3.14159
// Type inference
val name = "John" // String
val age = 25 // Int
val height = 1.75 // Double
Explicit Type Declaration
var message: String = "Hello"
var number: Int = 42
var decimal: Double = 3.14
Functions
Basic Function
fun greet(name: String): String {
return "Hello, $name!"
}
Single-Expression Function
fun square(x: Int) = x * x
Function with Default Parameters
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"
Control Flow
If Expression
val max = if (a > b) a else b
// Multi-line if
val max = if (a > b) {
println("Choose a")
a
} else {
println("Choose b")
b
}
When Expression (Switch)
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> print("x is neither 1 nor 2")
}
For Loop
// Range
for (i in 1..5) {
print(i)
}
// List
val items = listOf("apple", "banana", "orange")
for (item in items) {
println(item)
}
// With index
for ((index, value) in items.withIndex()) {
println("$index: $value")
}
Collections
Lists
// Immutable list
val numbers = listOf(1, 2, 3, 4, 5)
// Mutable list
val mutableNumbers = mutableListOf(1, 2, 3)
mutableNumbers.add(4)
Maps
// Immutable map
val map = mapOf(
"a" to 1,
"b" to 2,
"c" to 3
)
// Mutable map
val mutableMap = mutableMapOf("a" to 1)
mutableMap["b"] = 2
String Templates
val name = "Alice"
println("Hello, $name!")
println("Hello, ${name.toUpperCase()}!")
Null Safety
// Nullable type
var nullableName: String? = null
// Safe call
val length = nullableName?.length
// Elvis operator
val length = nullableName?.length ?: 0
// Not-null assertion
val length = nullableName!!.length
Classes
class Person(
val name: String,
var age: Int
) {
fun greet() = "Hello, I'm $name"
}
Data Classes
data class User(
val name: String,
val email: String,
var age: Int
)
Conclusion
Kotlin’s syntax is designed to be:
- Concise and expressive
- Safe and null-aware
- Interoperable with Java
- Easy to read and maintain
These features make Kotlin an excellent choice for modern Android development and other JVM-based projects.
Stay tuned for our next post where we’ll dive deeper into Kotlin’s variables and constants!