</>
Skip to content
Kotlin lessons (4/33)

Kotlin — Syntax

Variables

fun main() {
    // val: immutable
    val name = "Alice"
    val age: Int = 30

    // var: mutable
    var count = 0
    count++

    println("$name is $age years old")
}

Functions

// Basic function
fun add(a: Int, b: Int): Int {
    return a + b
}

// Expression body
fun multiply(a: Int, b: Int) = a * b

// Default parameters
fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name!")
}

// Named arguments
greet(name = "Bob", greeting = "Hi")

// Single expression
fun square(x: Int) = x * x

fun main() {
    println(add(3, 4))
    println(multiply(3, 4))
    greet("Alice")
}

Null safety

var name: String? = null

// Safe call
println(name?.length) // null

// Elvis operator
val length = name?.length ?: 0

// Non-null assertion (use carefully!)
// println(name!!.length) // Throws if null

// Safe cast
val obj: Any = "hello"
val str: String? = obj as? String

Control flow

// if/else
val x = 10
val label = if (x > 5) "big" else "small"

// when (like switch)
when (x) {
    1 -> println("one")
    2 -> println("two")
    in 3..10 -> println("between 3 and 10")
    else -> println("other")
}

// for loop
for (i in 1..5) {
    println(i)
}

// while
var y = 0
while (y < 5) {
    y++
}

String templates

val name = "Alice"
val age = 30

println("Name: $name")
println("Age: ${age + 1}")
println("Uppercase: ${name.uppercase()}")

Collections

// List
val nums = listOf(1, 2, 3, 4, 5)

// Mutable list
val mutable = mutableListOf(1, 2, 3)
mutable.add(4)

// Map
val map = mapOf("Alice" to 30, "Bob" to 25)

// Set
val set = setOf(1, 2, 3, 2, 1) // [1, 2, 3]

Mini Practice

Write Kotlin code that:

  1. Uses val and var with type inference
  2. Creates a function with default parameters
  3. Uses null safety operators
  4. Demonstrates when expression

Up Next

In the next lesson, you'll learn about Variables — declarations and types in Kotlin.

Related Topics

Frequently Asked Questions about Syntax

What is Syntax in Kotlin?

Syntax is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Syntax?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Syntax.

Why is Syntax important in Kotlin?

Syntax is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.