Kotlin Programming Language

Introduction to Kotlin

Kotlin is a modern programming language that runs on the JVM and can be used for Android development, server-side development, and more. It offers both object-oriented and functional programming features.

Key Features:

  • 100% Java interoperability
  • Null safety
  • Coroutines for async programming
  • Extension functions
  • Smart casts
  • Data classes

Language Basics

Variables and Functions

// Variables
val readOnly = "This cannot be changed"  // Immutable
var mutable = "This can be changed"      // Mutable

// Type inference
val number = 42       // Int
val double = 42.0     // Double
val float = 42.0f     // Float
val long = 42L        // Long

// Explicit types
val explicitly: Int = 42
val nullableString: String? = null

// Functions
fun greet(name: String): String {
    return "Hello, $name!"
}

// Single-expression functions
fun add(a: Int, b: Int) = a + b

// Default arguments
fun greetWithTitle(
    name: String,
    title: String = "Mr."
) = "Hello, $title $name!"

// Named arguments
fun main() {
    println(greetWithTitle(title = "Dr.", name = "Smith"))
}

// Extension functions
fun String.addExclamation() = "$this!"
fun main() {
    println("Hello".addExclamation()) // Prints: Hello!
}

Control Flow

// When expression
fun describe(obj: Any): String =
    when (obj) {
        1 -> "One"
        "Hello" -> "Greeting"
        is Long -> "Long number"
        !is String -> "Not a string"
        else -> "Unknown"
    }

// Smart casts
fun processNumber(x: Any) {
    when (x) {
        is Int -> println(x + 1)
        is Double -> println(x + 1.0)
        else -> println("Not a number")
    }
}

// For loops
for (i in 1..10) {
    println(i)
}

// Collections iteration
val items = listOf("apple", "banana", "orange")
for (item in items) {
    println(item)
}

// While loops
var x = 0
while (x < 10) {
    println(x)
    x++
}

Object-Oriented Programming

Classes and Objects

// Data class
data class User(
    val name: String,
    val age: Int
)

// Class with constructor and properties
class Person(
    val name: String,
    var age: Int
) {
    // Secondary constructor
    constructor() : this("Unknown", 0)
    
    // Property with custom getter
    val isAdult: Boolean
        get() = age >= 18
    
    // Method
    fun celebrateBirthday() {
        age++
        println("Happy Birthday! Now you are $age")
    }
}

// Object declaration (Singleton)
object DatabaseConfig {
    val url = "jdbc:mysql://localhost:3306/db"
    val username = "admin"
    
    fun connect() {
        println("Connecting to database...")
    }
}

// Companion object
class MyClass {
    companion object {
        fun create(): MyClass = MyClass()
    }
}

// Interface
interface Vehicle {
    val wheelCount: Int
    fun start()
    fun stop()
}

// Class implementing interface
class Car : Vehicle {
    override val wheelCount = 4
    
    override fun start() {
        println("Car is starting")
    }
    
    override fun stop() {
        println("Car is stopping")
    }
}

Functional Programming

Collections and Lambdas

// Lambda expressions
val sum = { x: Int, y: Int -> x + y }
println(sum(1, 2)) // Prints: 3

// Higher-order functions
fun operation(x: Int, y: Int, op: (Int, Int) -> Int): Int {
    return op(x, y)
}

// Collection operations
val numbers = listOf(1, 2, 3, 4, 5)

// Map
val doubled = numbers.map { it * 2 }

// Filter
val even = numbers.filter { it % 2 == 0 }

// Reduce
val sum = numbers.reduce { acc, n -> acc + n }

// Sequence operations (lazy evaluation)
val result = numbers.asSequence()
    .map { it * 2 }
    .filter { it % 3 == 0 }
    .take(2)
    .toList()

// Scope functions
data class Person(var name: String, var age: Int)

Person("John", 20).apply {
    name = "Jane"
    age = 21
}

Person("John", 20).also {
    println("Created person: ${it.name}")
}

Person("John", 20).let {
    println("${it.name} is ${it.age}")
}

with(Person("John", 20)) {
    println("$name is $age")
}

Coroutines

Asynchronous Programming

// Basic coroutine
suspend fun fetchUser(): User {
    delay(1000) // Suspends coroutine for 1 second
    return User("John", 30)
}

// Coroutine scope
fun main() = runBlocking {
    launch {
        println("Starting")
        delay(1000)
        println("Done")
    }
}

// Async/Await
suspend fun fetchUserAndPosts() = coroutineScope {
    val user = async { fetchUser() }
    val posts = async { fetchPosts() }
    
    // Wait for both results
    ProcessResult(user.await(), posts.await())
}

// Flow
fun numbers(): Flow = flow {
    for (i in 1..3) {
        delay(100)
        emit(i)
    }
}

fun main() = runBlocking {
    numbers()
        .map { it * 2 }
        .filter { it > 2 }
        .collect { println(it) }
}

// Error handling
suspend fun fetchData() = coroutineScope {
    try {
        val result = async { 
            throw Exception("Error") 
        }
        result.await()
    } catch (e: Exception) {
        println("Caught: ${e.message}")
    }
}

Android Development

Android with Kotlin

// Activity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // View binding
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // Click listener
        binding.button.setOnClickListener {
            // Handle click
        }
    }
}

// ViewModel
class UserViewModel : ViewModel() {
    private val _user = MutableLiveData()
    val user: LiveData = _user
    
    fun loadUser(id: String) {
        viewModelScope.launch {
            val result = repository.fetchUser(id)
            _user.value = result
        }
    }
}

// Jetpack Compose
@Composable
fun UserCard(user: User) {
    Card(
        modifier = Modifier
            .padding(16.dp)
            .fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = user.name,
                style = MaterialTheme.typography.h6
            )
            Text(
                text = "Age: ${user.age}",
                style = MaterialTheme.typography.body1
            )
        }
    }
}

Android Development Tools:

  • Android Studio
  • Kotlin Android Extensions
  • View Binding
  • Data Binding
  • Jetpack Compose
  • Android KTX