Introduction to Kotlin

From A Technological Wiki
Revision as of 17:26, 19 January 2026 by Root (talk | contribs)
Jump to navigation Jump to search

Kotlin is a modern, statically typed programming language used by over 60% of professional Android developers. Designed to be concise, expressive, and safe, it runs on the Java Virtual Machine (JVM) and is fully interoperable with Java. While it is best known for Android development, Kotlin is a general-purpose language that compiles to JVM bytecode, JavaScript, or native code, making it suitable for server-side, web frontend, and multiplatform mobile applications.

History

Kotlin was developed by JetBrains, the company behind IntelliJ IDEA. The project started in 2010 with the goal of creating a language that was as expressive as Java but more concise and safer.

  • 2010: JetBrains unveils Project Kotlin.
  • 2012: JetBrains open-sources the project under the Apache 2 license.
  • 2016: Kotlin 1.0, the first official stable release, is launched.
  • 2017: Google announces first-class support for Kotlin on Android at Google I/O.
  • 2019: Google announces that Android development will be "Kotlin-first," recommending it as the preferred language for new Android projects.

Primary uses

Kotlin is versatile and supports various development targets:

  • Android development: The primary language for building modern Android applications, replacing Java as the recommended standard.
  • Server-Side development: Frameworks like Spring Boot and Ktor allow developers to build scalable backend systems using Kotlin.
  • Web frontend: Kotlin/JS allows developers to write type-safe frontend code that transpiles to JavaScript.
  • Multiplatform mobile: Kotlin Multiplatform (KMP) enables sharing business logic between Android and iOS while keeping the UI native.
  • Data science: Kotlin provides libraries like KotlinDL and DataFrame for data analysis and machine learning.

Comparison: Kotlin vs. Flutter

Comparing Kotlin and Flutter effectively involves distinguishing between a programming language and a UI framework.

Feature Kotlin Flutter
Definition A general-purpose programming language. A UI toolkit (SDK) that uses the Dart language.
Architecture Native execution (JVM/ART). Uses the Skia graphics engine to render its own UI.
Performance Native performance; direct access to hardware. Near-native performance; may have overhead in complex graphics.
Platform Sharing Shared business logic (KMP); native UI. Shared UI and logic (Single codebase for all).
Best For Native Android apps requiring deep hardware integration or existing Java projects. Startups or apps requiring identical UI on iOS and Android quickly.

Comparison: Kotlin vs. Java

Kotlin was designed to address common pain points in Java.

  • Null Safety: Kotlin's type system distinguishes between nullable and non-nullable references, eliminating most NullPointerExceptions at compile time.
  • Conciseness: Kotlin drastically reduces boilerplate code. A standard POJO (Plain Old Java Object) with getters, setters, equals(), hashCode(), and toString() can be replaced by a single line in Kotlin.
  • Coroutines: Kotlin uses lightweight threads called coroutines for asynchronous programming, whereas Java traditionally relies on heavy OS threads (though virtual threads are being introduced in newer Java versions).
  • Interoperability: Kotlin can call Java code and vice versa without any bridge, allowing gradual migration of codebases.

Programming examples

Hello World

The entry point of a Kotlin application is the main function. Semicolons are optional.

fun main() {
    println("Hello, World!")
}

Variables and Types

Kotlin uses strict type inference. `val` creates an immutable variable (read-only), while `var` creates a mutable variable.

fun main() {
    val languageName = "Kotlin" // Inferred as String
    val launchYear = 2011       // Inferred as Int
    // languageName = "Java"    // Error: Val cannot be reassigned

    var users = 100
    users += 1                  // Valid
    
    println("Language: $languageName, Released: $launchYear")
}

Data Classes

In Java, creating a class to hold data requires verbose setup. In Kotlin, the `data` keyword automatically generates `equals()`, `hashCode()`, `toString()`, and `copy()` functions.

data class User(val name: String, val id: Int)

fun main() {
    val user1 = User("Alice", 101)
    val user2 = user1.copy(name = "Bob")
    
    println(user1) // Output: User(name=Alice, id=101)
    println(user2) // Output: User(name=Bob, id=101)
}

Null Safety

Kotlin forces you to handle null values explicitly.

fun main() {
    var nonNullable: String = "Hello"
    // nonNullable = null // Compilation Error

    var nullable: String? = "Hello"
    nullable = null       // Allowed

    // Safe call operator ?.
    println(nullable?.length) // Prints "null" instead of crashing
    
    // Elvis operator ?: (provides a default value if null)
    val length = nullable?.length ?: 0
}

Complex Example: Coroutines

This example demonstrates asynchronous programming using Coroutines. It simulates fetching data from a network without blocking the main thread.

import kotlinx.coroutines.*

// Simulating a network call
suspend fun fetchDataFromNetwork(): String {
    delay(1000L) // Non-blocking delay for 1 second
    return "Data loaded successfully"
}

fun main() = runBlocking {
    println("App started...")

    // Launch a new coroutine asynchronously
    val deferredResult = async {
        println("Fetching data...")
        fetchDataFromNetwork()
    }

    println("Main thread is free to do other work here.")
    
    // Wait for the result
    val result = deferredResult.await()
    println("Result: $result")
    println("App finished.")
}