0% found this document useful (0 votes)
27 views15 pages

Kotlin Course

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views15 pages

Kotlin Course

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Kotlin: From Zero to Practical

A concise course covering Kotlin fundamentals to intermediate topics, with examples and exercises.

Author: Generated by ChatGPT


Contents
1. Course Overview & Setup
2. Basics: Types, Variables, and Operators
3. Control Flow & Functions
4. Object-Oriented Programming (Classes & Objects)
5. Inheritance, Interfaces & Abstract Classes
6. Collections & Generics
7. Exceptions & Error Handling
8. Functional Programming & Lambdas
9. Coroutines & Asynchronous Programming
10. File I/O & Serialization
11. Networking & HTTP
12. Project: Simple To-Do App (Console or Android)
Appendix: Cheatsheet & Answers
1. Course Overview & Setup
What you'll learn: Kotlin syntax, OOP, functional programming, coroutines, and a small project. Tools:
IntelliJ IDEA, Android Studio, or Kotlin CLI.
Exercises:
- Install Kotlin (via IntelliJ or SDKMAN) and run `kotlinc [Link] -include-runtime -d [Link]`.
2. Basics: Types, Variables, and Operators
Kotlin supports val (immutable) and var (mutable). Types include Int, Double, Boolean, String, nullable
types with `?`. Operators similar to Java.
fun main() {
val name: String = "Ada"
var age: Int = 30
println("Hello $name, age $age")
}

Exercises:
- Declare variables of each type and print them.
3. Control Flow & Functions
Kotlin has if/else as expressions, when (like switch), loops (for, while). Functions can have default and
named parameters, single-expression syntax.
fun add(a: Int, b: Int): Int = a + b

fun main() {
for (i in 1..5) println(i)
println(add(2, 3))
}

Exercises:
- Write a function to compute factorial iteratively and recursively.
4. Object-Oriented Programming (Classes & Objects)
Classes have properties, methods, constructors. Data classes for simple models. Access modifiers:
private/protected/public/internal.
data class User(val name: String, val age: Int)

fun main() {
val u = User("Ada", 30)
println(u)
}

Exercises:
- Create a `Book` data class with title, author, and year.
5. Inheritance, Interfaces & Abstract Classes
Classes are final by default. Use `open` for inheritance. Interfaces define contracts. Abstract classes can
include implementation.
open class Animal {
open fun speak() = println("...")
}
class Dog: Animal() {
override fun speak() = println("Woof")
}

Exercises:
- Design an interface `Drawable` and implement it in two classes.
6. Collections & Generics
Immutable collections (listOf, mapOf) and mutable ones (mutableListOf, mutableMapOf). Generics with
variance (`in`, `out`).
val names = listOf("Sam", "Lee")
for (n in names) println(n)

Exercises:
- Given a list of integers, return a map of value -> frequency.
7. Exceptions & Error Handling
Kotlin has try/catch/finally. No checked exceptions. Throw with `throw`. Use `?` and `?:` to handle nulls
gracefully.
try {
val text = File("[Link]").readText()
} catch (e: Exception) {
println([Link])
}

Exercises:
- Create a custom exception and throw it when invalid input is given.
8. Functional Programming & Lambdas
Functions are first-class. Use higher-order functions, lambdas, extension functions. Scope functions: let,
apply, run, also, with.
val nums = listOf(1,2,3,4,5)
val evens = [Link] { it % 2 == 0 }.map { it * it }

Exercises:
- Use map and filter to process a list of numbers.
9. Coroutines & Asynchronous Programming
Coroutines are lightweight threads. Use `launch` and `async` from [Link]. Suspend functions
with `suspend` keyword.
import [Link].*

fun main() = runBlocking {


launch {
delay(500)
println("Half second later")
}
}

Exercises:
- Write a coroutine that fetches data from a web API using Ktor client.
10. File I/O & Serialization
Use [Link] or Kotlin extensions for files. Use [Link] for JSON.
File("[Link]").writeText("Hello")
val text = File("[Link]").readText()

Exercises:
- Read a CSV file and parse records into objects.
11. Networking & HTTP
Use Ktor client or OkHttp for HTTP requests. Deserialize JSON responses.
val client = HttpClient()
val res: String = [Link]("[Link]
println(res)

Exercises:
- Call a public REST API and print a field from JSON response.
12. Project: Simple To-Do App (Console or Android)
Outline: Create a console or Android app that allows adding, listing, completing, and removing tasks.
Persist tasks to a JSON file.
data class Task(var text: String, var done: Boolean = false) {
fun complete() { done = true }
override fun toString() = (if (done) "[x]" else "[ ]") + " " + text
}
Project Steps:
- Create Task class and TaskManager with a MutableList.
- Implement console menu: add, list, complete, delete, save, load.
- Persist tasks to a JSON file using [Link].
- (Optional) Create an Android UI with RecyclerView.
Appendix: Kotlin Cheatsheet
Declaration val x = 5; var y: String = "hi"
Class data class User(val name: String)
Collections listOf(1,2,3), mutableMapOf("a" to 1)
Lambda [Link] { it > 0 }.map { it*2 }
Coroutine runBlocking { launch { delay(1000) } }

Answers (selected)
Factorial (recursive) example:
fun fact(n: Int): Int = if (n <= 1) 1 else n * fact(n-1)
LINQ-style map/filter example:
val avg = [Link]()

You might also like