Fundamentals
Kotlin Programming Basics
Introduction to Kotlin
Kotlin is a modern programming language that makes developers happier. It's concise, safe, interoperable with Java, and provides many features that help you avoid common programming errors.
Key Features of Kotlin
- Null Safety
- Extension Functions
- Data Classes
- Coroutines for asynchronous programming
- Higher-Order Functions
Basic Syntax
Let's look at some basic Kotlin syntax:
// Variables
val readOnly = "I can't be changed" // Val is immutable
var mutable = "I can be changed" // Var is mutable
// Functions
fun sayHello(name: String): String {
return "Hello, $name!"
}
// Single-expression functions
fun double(x: Int) = x * 2
// Null safety
var nullable: String? = null
val length = nullable?.length ?: 0
// When expression (switch-case replacement)
when (x) {
1 -> print("x is 1")
2 -> print("x is 2")
else -> print("x is neither 1 nor 2")
}
Classes and Objects
Kotlin makes creating classes and objects simple:
// Simple class
class Person(val name: String, var age: Int)
// Data class
data class User(val name: String, val email: String)
// Singleton
object DatabaseConnection {
fun connect() = println("Connected to database")
}
// Companion object (similar to static methods)
class MyClass {
companion object {
fun create(): MyClass = MyClass()
}
}
Extension Functions
One of Kotlin's most powerful features is the ability to extend existing classes:
fun String.addExclamation(): String {
return this + "!"
}
val message = "Hello".addExclamation() // Returns "Hello!"
Coroutines
Kotlin's approach to asynchronous programming:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}