Kotlin Notes
1. Introduction
What is Kotlin?
Kotlin is a modern, statically typed programming language developed by JetBrains. It is fully
interoperable with Java and is widely used for Android development, server-side
applications, and more.
Features of Kotlin:
• Concise: Reduces boilerplate code compared to Java.
• Expressive: Easy to read and write.
• Interoperable: Works seamlessly with Java and existing Java libraries.
• Null Safety: Eliminates null pointer exceptions with built-in null safety features.
• Functional & Object-Oriented: Supports both paradigms.
• Coroutines: Supports asynchronous programming for better performance.
2. Kotlin Basics
Variables and Data Types
Immutable (val): Read-only variables.
Mutable (var): Can be reassigned.
Example:
val name: String = "Dhruv"
var age: Int = 17
Control Flow
• If-else (expression-based)
• When (replacement for switch-case)
• Loops (for, while, do-while)
Example:
val result = if (age > 18) "Adult" else "Minor"
3. Functions
Defining Functions
fun greet(name: String): String {
return "Hello, $name!"
}
Single-expression Functions
fun square(x: Int) = x * x
4. Classes
Defining a Class
class Person(val name: String, var age: Int) {
fun introduce() {
println("My name is $name and I am $age years old.")
}
}
5. Kotlin Essentials: Beyond the Basics
Extension Functions
fun String.reverse() = this.reversed()
println("Kotlin".reverse()) // "niltok"
Data Classes
data class User(val name: String, val age: Int)
6. Functional Manipulation
Higher-Order Functions
fun operate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}