CODY ← Back to Courses
Kt

Kotlin — Modern Android Development

Kotlin is a modern, concise, and safe programming language that runs on the JVM. It's the official language for Android development, praised for its expressive syntax and null safety features.

Android Official Concise & Safe JVM Compatible

What is Kotlin?

Kotlin is a modern programming language developed by JetBrains. It's fully interoperable with Java, runs on the JVM, and is the preferred language for Android development since 2017. Kotlin combines object-oriented and functional programming features with a clean, expressive syntax.

📱 Android First

Official language for Android development. Google provides first-class support with Jetpack Compose.

🛡️ Null Safety

Type system eliminates null pointer exceptions at compile time.

✍️ Concise

Reduces boilerplate code by ~40% compared to Java while being fully interoperable.

Basic Syntax

Kotlin syntax is clean and expressive. No semicolons required, type inference, and concise data classes.

hello world
// This is a comment
fun main() {
    // Variables
    val name = "Alice"  // Immutable (like final in Java)
    var age = 25        // Mutable
    
    // Type inference
    val pi: Double = 3.14159  // Explicit type
    val isActive = true
    
    // String templates
    println("Hello, $name! You are $age years old.")
    
    // Expression body
    fun add(a: Int, b: Int) = a + b
    
    // When expression (replaces switch)
    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89 -> "B"
        else -> "C"
    }
}

Null Safety

Kotlin's type system distinguishes between nullable and non-nullable types, eliminating NullPointerExceptions.

null safety
// Non-nullable type (cannot be null)
var name: String = "Alice"
// name = null // Compilation error!

// Nullable type (can be null)
var middleName: String? = "Marie"
middleName = null  // Allowed

// Safe call operator ?.
val length = middleName?.length  // Returns null if middleName is null

// Elvis operator ?: (provide default)
val len = middleName?.length ?: 0

// Not-null assertion !! (use carefully!)
val forcedLen = middleName!!.length  // Throws NPE if null

// Safe casts
val obj: Any = "Hello"
val str = obj as? String  // Safe cast, returns null if fails

// let for executing code on non-null values
middleName?.let {
    println("Middle name is $it")  // Only executes if not null
}

Functions & Lambdas

Kotlin supports functional programming with lambda expressions, higher-order functions, and extension functions.

functions and lambdas
// Default parameters
fun greet(name: String, prefix: String = "Hello") = "$prefix, $name!"
println(greet("Alice"))  // "Hello, Alice!"
println(greet("Bob", "Hi"))  // "Hi, Bob!"

// Named arguments
fun createUser(name: String, age: Int, city: String) { ... }
createUser(name = "Alice", city = "NYC", age = 30)  // Order doesn't matter

// Lambda expression
val square: (Int) -> Int = { x -> x * x }
println(square(5))  // 25

// Higher-order function (function that takes a function)
fun repeat(times: Int, action: () -> Unit) {
    for (i in 1..times) action()
}
repeat(3) { println("Hello!") }

// Extension function
fun String.reverseWords(): String = this.split(" ").reversed().joinToString(" ")
println("Hello World".reverseWords())  // "World Hello"

// Infix functions
infix fun Int.`**`(power: Int): Int = Math.pow(this.toDouble(), power.toDouble()).toInt()
println(2 `**` 3)  // 8

Classes & Data Classes

Kotlin classes are concise. Data classes automatically generate equals, hashCode, toString, and copy methods.

classes
// Simple class with primary constructor
class Person(val name: String, var age: Int) {
    // Initializer block
    init {
        println("Created person: $name")
    }
    
    // Secondary constructor
    constructor(name: String) : this(name, 0)
    
    // Method
    fun greet() = "Hello, I'm $name"
}

// Data class (auto-generates toString, equals, hashCode, copy)
data class User(
    val id: Int,
    val username: String,
    val email: String
)

// Using data class
val user1 = User(1, "alice", "alice@email.com")
val user2 = user1.copy(username = "alice_new")  // Copy with changes

// Sealed classes (restricted class hierarchies)
sealed class Result<T> {
    data class Success<T>(val data: T) : Result()
    data class Error(val message: String) : Result()
    object Loading : Result()
}

// Object declaration (singleton)
object AppConfig {
    const val API_URL = "https://api.example.com"
    var debugMode = false
}

// Companion object (like static members)
class Database {
    companion object {
        fun getInstance() = Database()
    }
}

Collections & Sequences

Kotlin has a rich collection API with immutable and mutable collections, plus functional operations.

collections
// Immutable collections (read-only)
val numbers = listOf(1, 2, 3, 4, 5)
val names = setOf("Alice", "Bob", "Charlie")
val scores = mapOf("Alice" to 95, "Bob" to 87)

// Mutable collections
val mutableNumbers = mutableListOf(1, 2, 3)
mutableNumbers.add(4)
mutableNumbers.removeAt(0)

// Collection operations
val doubled = numbers.map { it * 2 }  // [2,4,6,8,10]
val evens = numbers.filter { it % 2 == 0 }  // [2,4]
val sum = numbers.reduce { acc, i -> acc + i }  // 15
val anyEven = numbers.any { it % 2 == 0 }  // true
val allPositive = numbers.all { it > 0 }  // true

// Chaining operations (eager)
val result = numbers
    .filter { it > 2 }
    .map { it * it }
    .take(2)  // [9,16]

// Sequences (lazy evaluation for performance)
val lazyResult = numbers.asSequence()
    .filter { it > 2 }
    .map { it * it }
    .take(2)
    .toList()  // Executes only when needed

// Group by
val people = listOf("Alice" to 25, "Bob" to 30, "Charlie" to 25)
val byAge = people.groupBy { it.second }  // Map: 25->[Alice,Charlie], 30->[Bob]

// Associate by
val nameToAge = people.associate { it.first to it.second }  // Map: Alice=25, Bob=30, Charlie=25

Coroutines — Asynchronous Programming

Coroutines simplify asynchronous programming, making concurrent code easier to write and understand.

coroutines
// Add dependency: implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")

import kotlinx.coroutines.*

suspend fun fetchUserData(userId: Int): String {
    delay(1000)  // Simulate network call (non-blocking)
    return "User $userId"
}

fun main() = runBlocking {  // Creates a coroutine scope
    println("Start")
    
    // Launch a coroutine
    val job = launch {
        val user = fetchUserData(1)
        println("Fetched: $user")
    }
    
    // Async (returns a Deferred)
    val deferred = async {
        fetchUserData(2)
    }
    val result = deferred.await()  // Wait for result
    
    // Parallel execution
    val users = listOf(1, 2, 3).map { userId ->
        async { fetchUserData(userId) }
    }.awaitAll()
    
    println("All users: $users")
    job.join()  // Wait for launch to complete
}

// Coroutine scope and structured concurrency
class UserRepository {
    private val scope = CoroutineScope(Dispatchers.IO)
    
    fun fetchUsers() {
        scope.launch {
            val users = fetchUserData(1)
            withContext(Dispatchers.Main) {
                // Update UI on main thread
            }
        }
    }
    
    fun cleanup() {
        scope.cancel()  // Cancels all coroutines in this scope
    }
}
💡 Android Best Practice: Use `viewModelScope` in ViewModels and `lifecycleScope` in Activities/Fragments for automatic cancellation. Use `Dispatchers.IO` for network/database, `Dispatchers.Main` for UI updates.

🛠 Project: Weather App (Android-style)

Build a weather data class with API integration simulation using coroutines and data classes.

WeatherApp.kt
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.random.Random

// Data models
data class Weather(
    val city: String,
    val temperature: Double,
    val condition: String,
    val humidity: Int,
    val windSpeed: Double
)

sealed class WeatherState {
    object Loading : WeatherState()
    data class Success(val weather: Weather) : WeatherState()
    data class Error(val message: String) : WeatherState()
}

// Repository with simulated API
class WeatherRepository {
    private val conditions = listOf("Sunny", "Cloudy", "Rainy", "Stormy", "Snowy")
    
    suspend fun fetchWeather(city: String): Weather = withContext(Dispatchers.IO) {
        // Simulate network delay
        delay(1500)
        
        // Simulate random weather data
        val temp = Random.nextDouble(-10.0, 35.0)
        val condition = conditions.random()
        val humidity = Random.nextInt(20, 90)
        val windSpeed = Random.nextDouble(0.0, 30.0)
        
        Weather(city, temp, condition, humidity, windSpeed)
    }
    
    suspend fun fetchWeatherFlow(city: String): Flow<WeatherState> = flow {
        emit(WeatherState.Loading)
        try {
            val weather = fetchWeather(city)
            emit(WeatherState.Success(weather))
        } catch (e: Exception) {
            emit(WeatherState.Error(e.message ?: "Unknown error"))
        }
    }.flowOn(Dispatchers.IO)
}

// ViewModel (simplified)
class WeatherViewModel {
    private val repository = WeatherRepository()
    private val _weatherState = MutableStateFlow<WeatherState>(WeatherState.Loading)
    val weatherState: StateFlow<WeatherState> = _weatherState
    
    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    fun loadWeather(city: String) {
        scope.launch {
            repository.fetchWeatherFlow(city).collect { state ->
                _weatherState.value = state
            }
        }
    }
    
    fun cleanup() {
        scope.cancel()
    }
}

// Main function to simulate UI
suspend fun main() = coroutineScope {
    val viewModel = WeatherViewModel()
    
    // Collect weather state
    val job = launch {
        viewModel.weatherState.collect { state ->
            when (state) {
                is WeatherState.Loading -> println("⏳ Loading weather...")
                is WeatherState.Success -> {
                    val w = state.weather
                    println("""
                        |📍 City: ${w.city}
                        |🌡️ Temperature: ${"%.1f".format(w.temperature)}°C
                        |☁️ Condition: ${w.condition}
                        |💧 Humidity: ${w.humidity}%
                        |💨 Wind: ${"%.1f".format(w.windSpeed)} km/h
                    """.trimMargin())
                }
                is WeatherState.Error -> println("❌ Error: ${state.message}")
            }
        }
    }
    
    // Load weather for different cities
    viewModel.loadWeather("Almaty")
    delay(2000)
    viewModel.loadWeather("Astana")
    delay(2000)
    viewModel.loadWeather("New York")
    delay(3000)
    
    job.cancel()
    viewModel.cleanup()
}
🎯 Challenge: Add a real API using Retrofit and Kotlin Flow. Implement search history with Room database. Add temperature unit toggle (Celsius/Fahrenheit).