Introduction to Kotlin
Kotlin is a modern, statically-typed programming language developed by JetBrains, designed to be concise, safe, and interoperable with Java. It runs on the Java Virtual Machine (JVM) and is fully compatible with Java, making it popular for Android development, server-side applications, and more. Kotlin aims to reduce boilerplate code while enhancing readability and preventing common errors like null pointer exceptions. It was first released in 2011 and became officially supported for Android in 2017.
Key features include:
- Conciseness: Shorter syntax compared to Java.
- Null Safety: Built-in handling to avoid null-related crashes.
- Interoperability: Seamless integration with existing Java code.
- Coroutines: For asynchronous programming.
- Multiplatform Support: Can compile to JVM, JavaScript, Native, and more.
Basic Syntax
Kotlin programs are saved in files with a .kt extension. A simple “Hello, World!” program looks like this:
fun main() {
println("Hello, World!")
}
fundeclares a function.main()is the entry point.- No semicolons are required at the end of statements (though they’re optional).
- Comments use
//for single-line or/* */for multi-line.
Packages and imports are similar to Java but optional for simple programs.
Variables and Data Types
Variables are declared using val (immutable, like constants) or var (mutable). Kotlin infers types automatically, but you can specify them explicitly.
Basic data types include:
- Numbers:
Int,Long,Double,Float,Byte,Short. - Characters:
Char(e.g.,'a'). - Booleans:
Boolean(true/false). - Strings:
String(immutable sequences of characters).
Examples:
val name: String = "Alice" // Immutable, type specified
var age = 30 // Mutable, type inferred as Int
age = 31 // Can be reassigned
Strings support templates with $:
println("Hello, $name! You are $age years old.")
Functions
Functions are defined with fun, parameters with types, and return types after the parameters. Single-expression functions can use =.
Example:
fun add(a: Int, b: Int): Int {
return a + b
}
// Single-expression version
fun multiply(a: Int, b: Int) = a * b
Default arguments and named parameters make functions flexible:
fun greet(name: String = "World") = "Hello, $name!"
println(greet()) // Hello, World!
println(greet(name = "Bob")) // Hello, Bob!
Control Flow
Kotlin uses familiar structures like if, when (like switch), for, and while, but with enhancements.
- If-else can be expressions:
val max = if (a > b) a else b
- When for multiple conditions:
when (x) {
1 -> println("One")
in 2..10 -> println("Between 2 and 10")
else -> println("Other")
}
- Loops:
for (i in 1..5) { println(i) } // 1 to 5
while (condition) { /* code */ }
Classes and Objects
Kotlin is object-oriented with concise class syntax. Primary constructors are part of the class header.
Example:
class Person(val name: String, var age: Int) {
fun introduce() = "Hi, I'm $name and I'm $age years old."
}
val alice = Person("Alice", 30)
println(alice.introduce())
- Properties are auto-generated with getters/setters.
- Inheritance uses
:, and classes arefinalby default (useopento allow extension). - Data classes for simple data holders:
data class User(val id: Int, val name: String)auto-generatesequals(),hashCode(), etc.
Collections
Kotlin provides immutable and mutable collections like lists, sets, and maps.
Examples:
val numbers = listOf(1, 2, 3) // Immutable list
val mutableList = mutableListOf("a", "b")
mutableList.add("c")
val map = mapOf("key1" to 1, "key2" to 2)
Higher-order functions like filter, map are common:
val evens = numbers.filter { it % 2 == 0 }
Null Safety
One of Kotlin’s strengths is handling nulls. Types are non-nullable by default; use ? for nullable.
var str: String? = null // Nullable
val length = str?.length // Safe call, returns null if str is null
val upper = str!!.toUpperCase() // Non-null assertion (throws if null)
Use Elvis operator for defaults: val len = str?.length ?: 0
Getting Started
To practice, install IntelliJ IDEA (free Community Edition) or use the online Kotlin Playground. For Android, use Android Studio.
This covers the fundamentals; for deeper dives, explore coroutines, lambdas, or extensions.
