Kotlin with key concepts

Since you’ve asked again for a comprehensive Kotlin tutorial covering variables, data types, functions, classes, null safety, collections, lambdas, and coroutines (basic understanding), I’ll provide a fresh, concise, and beginner-friendly explanation of each topic with examples. I’ll assume you want a complete overview again, structured similarly to the previous response but with new examples to reinforce learning. If you meant something different (e.g., specific clarifications or advanced topics), please let me know!


1. Variables

Variables are used to store data. Kotlin has two types: val (cannot change) and var (can change).

Sub-topics:

  • Declaring Variables

  • Immutable (val) vs Mutable (var)

  • Type Inference

Explanation & Examples:

  • Declaring Variables: Use val or var, a name, and optionally a type.

  • Immutable (val): Fixed value after assignment.

  • Mutable (var): Value can be updated.

  • Type Inference: Kotlin guesses the type if not specified.

kotlin

fun main() {
    // Immutable variable
    val city = "Paris" // String inferred
    // city = "London" // Error: cannot reassign val

    // Mutable variable
    var temperature = 20 // Int inferred
    temperature = 22 // Works

    // Explicit type
    var distance: Double = 10.5

    println("City: $city, Temperature: $temperature°C, Distance: $distance km")
}

Output:

City: Paris, Temperature: 22°C, Distance: 10.5 km

2. Data Types

Data types define what kind of data a variable holds (e.g., numbers, text).

Sub-topics:

  • Basic Data Types: Int, Double, Float, Long, Char, String, Boolean

  • Type Conversion

Explanation & Examples:

  • Basic Data Types:

    • Numbers: Int (whole), Double (decimal), Float (smaller decimal), Long (large numbers).

    • Char: Single character (e.g., 'B').

    • String: Text (e.g., "Welcome").

    • Boolean: true or false.

  • Type Conversion: Convert types like Int to Double.

kotlin

fun main() {
    // Numbers
    val quantity: Int = 100
    val cost: Double = 29.99
    val height: Float = 1.75f
    val population: Long = 5000000L

    // Character
    val grade: Char = 'A'

    // String
    val message: String = "Welcome to Kotlin!"

    // Boolean
    val isOpen: Boolean = false

    // Type conversion
    val items: Int = 50
    val itemsDouble: Double = items.toDouble()

    println("Quantity: $quantity, Cost: $cost, Grade: $grade, Message: $message, IsOpen: $isOpen")
    println("Items as Double: $itemsDouble")
}

Output:

Quantity: 100, Cost: 29.99, Grade: A, Message: Welcome to Kotlin!, IsOpen: false
Items as Double: 50.0

3. Functions

Functions are reusable blocks of code that do a specific job.

Sub-topics:

  • Declaring Functions

  • Parameters and Return Types

  • Default and Named Parameters

Explanation & Examples:

  • Declaring Functions: Use fun, a name, and optional parameters/return type.

  • Parameters and Return Types: Pass data and return results.

  • Default and Named Parameters: Set defaults or call parameters by name.

kotlin

fun main() {
    // Simple function
    printGreeting()

    // Function with parameters and return
    val result = multiply(4, 5)
    println("Multiplication: $result")

    // Default and named parameters
    sendMessage("John")
    sendMessage(name = "Emma", message = "Good morning")
}

// Simple function
fun printGreeting() {
    println("Welcome!")
}

// Function with parameters and return
fun multiply(x: Int, y: Int): Int {
    return x * y
}

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

Output:

Welcome!
Multiplication: 20
Hello, John!
Good morning, Emma!

4. Classes

Classes are templates for creating objects, which combine data and behavior.

Sub-topics:

  • Creating Classes and Objects

  • Properties and Methods

  • Constructors

  • Inheritance

Explanation & Examples:

  • Creating Classes and Objects: Use class and create objects with ClassName().

  • Properties and Methods: Properties store data, methods define actions.

  • Constructors: Initialize objects with data.

  • Inheritance: A class can extend another using : BaseClass().

kotlin

fun main() {
    // Create object
    val car = Car("Toyota", 2023)
    car.drive()

    // Inheritance
    val electricCar = ElectricCar("Tesla", 2024, 75.0)
    electricCar.drive()
    electricCar.checkBattery()
}

// Simple class
class Car(val brand: String, var year: Int) {
    fun drive() {
        println("$brand ($year) is driving.")
    }
}

// Inheritance
open class Vehicle(val brand: String, var year: Int) {
    open fun drive() {
        println("$brand ($year) is moving.")
    }
}

class ElectricCar(brand: String, year: Int, val batteryLevel: Double) : Vehicle(brand, year) {
    override fun drive() {
        println("$brand ($year) is driving silently.")
    }

    fun checkBattery() {
        println("Battery level: $batteryLevel%")
    }
}

Output:

Toyota (2023) is driving.
Tesla (2024) is driving silently.
Battery level: 75.0%

5. Null Safety

Kotlin’s null safety prevents crashes from null values.

Sub-topics:

  • Nullable Types

  • Safe Calls (?.)

  • Elvis Operator (?:)

  • Non-Null Assertion (!!)

Explanation & Examples:

  • Nullable Types: Add ? to allow null (e.g., String?).

  • Safe Calls (?.): Access properties/methods only if not null.

  • Elvis Operator (?:): Provide a default if null.

  • Non-Null Assertion (!!): Assume not null (risky).

kotlin

fun main() {
    // Nullable type
    var username: String? = "Sarah"
    println("Username length: ${username?.length}") // Safe call

    username = null
    println("Username length: ${username?.length}") // Null

    // Elvis operator
    val length = username?.length ?: -1
    println("Length with default: $length")

    // Non-null assertion
    val text: String? = "Learn Kotlin"
    val textLength = text!!.length // Safe here
    println("Text length: $textLength")
}

Output:

Username length: 5
Username length: null
Length with default: -1
Text length: 12

6. Collections

Collections hold multiple items, like lists, sets, or maps.

Sub-topics:

  • List: Ordered, allows duplicates.

  • Set: Unordered, no duplicates.

  • Map: Key-value pairs.

  • Mutable vs Immutable Collections

Explanation & Examples:

  • List: Use listOf() (immutable) or mutableListOf() (mutable).

  • Set: Use setOf() or mutableSetOf().

  • Map: Use mapOf() or mutableMapOf().

  • Mutable vs Immutable: Immutable can’t change; mutable can.

kotlin

fun main() {
    // Immutable List
    val colors = listOf("Red", "Blue", "Green")
    println("Colors: $colors")

    // Mutable List
    val scores = mutableListOf(85, 90, 95)
    scores.add(100)
    println("Scores: $scores")

    // Set
    val uniqueItems = setOf(1, 2, 2, 3) // No duplicates
    println("Unique Items: $uniqueItems")

    // Map
    val grades = mapOf("Math" to 90, "Science" to 88)
    println("Grades: $grades")
    println("Math grade: ${grades["Math"]}")
}

Output:

Colors: [Red, Blue, Green]
Scores: [85, 90, 95, 100]
Unique Items: [1, 2, 3]
Grades: {Math=90, Science=88}
Math grade: 90

7. Lambdas

Lambdas are short, unnamed functions, often used with collections.

Sub-topics:

  • Lambda Syntax

  • Using Lambdas with Collections

  • Higher-Order Functions

Explanation & Examples:

  • Lambda Syntax: { params -> code }.

  • Using Lambdas with Collections: For operations like filter, map.

  • Higher-Order Functions: Functions that accept lambdas.

kotlin

fun main() {
    // Simple lambda
    val cube = { x: Int -> x * x * x }
    println("Cube of 3: ${cube(3)}")

    // Lambdas with collections
    val numbers = listOf(10, 15, 20, 25)
    val multiplesOfFive = numbers.filter { it % 5 == 0 }
    println("Multiples of 5: $multiplesOfFive")

    val tripled = numbers.map { it * 3 }
    println("Tripled: $tripled")

    // Higher-order function
    fun applyOperation(value: Int, op: (Int) -> Int): Int {
        return op(value)
    }
    val result = applyOperation(5) { it + 2 }
    println("Result: $result")
}

Output:

Cube of 3: 27
Multiples of 5: [10, 15, 20, 25]
Tripled: [30, 45, 60, 75]
Result: 7

8. Coroutines (Basic Understanding)

Coroutines simplify asynchronous tasks (e.g., fetching data) without blocking the program.

Sub-topics:

  • What are Coroutines?

  • Basic Coroutine Functions: launch, async

  • Suspending Functions

Explanation & Examples:

  • What are Coroutines?: They handle tasks like delays or network calls efficiently.

  • Basic Coroutine Functions:

    • launch: Starts a coroutine, no result.

    • async: Starts a coroutine, returns a result with .await().

  • Suspending Functions: Marked with suspend, they pause/resume.

Note: Requires kotlinx-coroutines-core library. Assume it’s included.

kotlin

import kotlinx.coroutines.*

fun main() = runBlocking {
    // Launch coroutine
    launch {
        delay(1000) // Non-blocking delay
        println("Coroutine finished!")
    }

    // Async coroutine
    val deferred = async {
        delay(500)
        "Kotlin Coroutines"
    }
    println("Async result: ${deferred.await()}")

    // Suspend function
    val result = fetchData()
    println("Fetched: $result")

    println("Main continues")
}

// Suspend function
suspend fun fetchData(): String {
    delay(300)
    return "Data loaded"
}

Output (order may vary):

Main continues
Async result: Kotlin Coroutines
Fetched: Data loaded
Coroutine finished!

Summary

You’ve covered Kotlin’s core concepts:

  • Variables: val (fixed), var (changeable), type inference.

  • Data Types: Numbers, Char, String, Boolean, type conversion.

  • Functions: Declare, use parameters, default/named parameters.

  • Classes: Objects, properties, methods, constructors, inheritance.

  • Null Safety: Nullable types, safe calls, Elvis operator, !!.

  • Collections: List, Set, Map, mutable/immutable.

  • Lambdas: Syntax, collections, higher-order functions.

  • Coroutines: Basics of launch, async, suspend functions.

These examples are simple and practical. To deepen your understanding, try:

  • Writing a small app (e.g., a shopping list).

  • Experimenting with coroutines for delays or fake API calls.

  • Combining lambdas and collections for data processing.

If you want more details, specific exercises, or clarification on any topic, let me know!

0
Subscribe to my newsletter

Read articles from Singaraju Saiteja directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Singaraju Saiteja
Singaraju Saiteja

I am an aspiring mobile developer, with current skill being in flutter.