Kotlin Tutorial
Kotlin is a modern, statically typed programming language developed by JetBrains. It is designed to be fully interoperable with Java and is often used for Android development, backend services, and more.
1. Setting Up Kotlinβ
Installing the Kotlin Compilerβ
-
Using SDKMAN (for Mac and Linux):
sdk install kotlin -
Manual Download: Download the compiler from the Kotlin website.
Using Kotlin in an IDEβ
JetBrains' IntelliJ IDEA provides the best support for Kotlin. Download IntelliJ IDEA Community Edition, which includes Kotlin support.
2. Basic Kotlin Syntaxβ
Hello World Programβ
fun main() {
println("Hello, Kotlin!")
}
Variablesβ
Kotlin has two types of variables:
val(immutable)var(mutable)
val name = "Alice" // Immutable
var age = 25 // Mutable
3. Control Flowβ
Conditional Statementsβ
val age = 18
if (age >= 18) {
println("You are an adult.")
} else {
println("You are a minor.")
}
When Expressionβ
The when expression in Kotlin is similar to switch in other languages.
val day = 3
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
else -> "Unknown"
}
println(dayName)
4. Functionsβ
Functions in Kotlin can have default arguments and return types.
Example Functionβ
fun greet(name: String = "Guest") {
println("Hello, $name!")
}
fun add(a: Int, b: Int): Int {
return a + b
}
Single-Expression Functionsβ
fun multiply(a: Int, b: Int) = a * b
5. Classes and Objectsβ
Kotlin is an object-oriented language and provides classes to represent objects.
Defining a Classβ
class Person(val name: String, var age: Int) {
fun greet() {
println("Hello, my name is $name and I am $age years old.")
}
}
val person = Person("Alice", 30)
person.greet()
Data Classesβ
Data classes are used for classes that only hold data.
data class User(val id: Int, val name: String)
val user = User(1, "Alice")
println(user)
6. Null Safetyβ
Kotlinβs type system helps eliminate NullPointerException by differentiating between nullable and non-nullable types.
Nullable Typesβ
var name: String? = "Alice"
name = null
// Safe call
println(name?.length)
// Elvis operator
val length = name?.length ?: 0
7. Collectionsβ
Kotlin has built-in support for collections such as Lists, Sets, and Maps.
Listβ
val names = listOf("Alice", "Bob", "Charlie")
println(names[1])
Mutable Listβ
val mutableNames = mutableListOf("Alice", "Bob")
mutableNames.add("Charlie")
8. Lambdas and Higher-Order Functionsβ
Kotlin supports functional programming features, including lambdas and higher-order functions.
Lambda Expressionβ
val square = { x: Int -> x * x }
println(square(5))
Higher-Order Functionβ
fun operate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
val sum = operate(3, 4) { a, b -> a + b }
println(sum)
9. Extensionsβ
Extensions add functionality to existing classes without modifying their source code.
Exampleβ
fun String.greet() = "Hello, $this!"
println("Alice".greet())
10. Coroutinesβ
Kotlin coroutines provide a way to handle asynchronous code.
Coroutine Exampleβ
Add the dependency in your build.gradle:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2")
Launching a Coroutineβ
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
Summaryβ
This tutorial covered:
- Setting up Kotlin and writing a basic program.
- Using variables, control flow, and functions.
- Creating classes, handling null safety, and working with collections.
- Using lambdas, extensions, and coroutines for asynchronous programming.
Kotlin is a versatile language with concise syntax, making it suitable for a wide range of applications.
Content Reviewβ
The content in this repository has been reviewed by chevp. Chevp is dedicated to ensuring that the information provided is accurate, relevant, and up-to-date, helping users to learn and implement programming skills effectively.
About the Reviewerβ
For more insights and contributions, visit chevp's GitHub profile: chevp's GitHub Profile.