Quick Start
Overview
This chapter will quickly introduce Kotlin's core features through practical code examples. We'll start with the simplest "Hello World" program and progressively demonstrate Kotlin's powerful capabilities.
Your First Kotlin Program
Hello World
kotlin
fun main() {
println("Hello, Kotlin!")
}Key Points:
funkeyword defines a functionmain()is the program entry pointprintln()outputs text with newline- No semicolon required at end (optional)
main Function with Parameters
kotlin
fun main(args: Array<String>) {
if (args.isNotEmpty()) {
println("Hello, ${args[0]}!")
} else {
println("Hello, World!")
}
}Variables and Constants
Variable Declaration
kotlin
fun main() {
// Mutable variable (var)
var name = "Kotlin" // Type inference
var age: Int = 25 // Explicit type declaration
name = "Kotlin 1.9" // Can reassign
age = 26
// Immutable variable (val)
val language = "Kotlin"
val version = 1.9
// language = "Java" // Compile error! val cannot be reassigned
println("Language: $language, Version: $version")
println("Name: $name, Age: $age")
}Null Safety
kotlin
fun main() {
// Non-null type
var name: String = "Kotlin"
// name = null // Compile error!
// Nullable type
var nullableName: String? = "Kotlin"
nullableName = null // Allowed
// Safe call
println("Length: ${nullableName?.length}")
// Elvis operator
val length = nullableName?.length ?: 0
println("Length with default: $length")
// Non-null assertion (use with caution)
nullableName = "Kotlin"
println("Definite length: ${nullableName!!.length}")
}Basic Data Types
kotlin
fun main() {
// Numeric types
val byte: Byte = 127
val short: Short = 32767
val int: Int = 2147483647
val long: Long = 9223372036854775807L
val float: Float = 3.14f
val double: Double = 3.14159265359
// Character and Boolean
val char: Char = 'K'
val boolean: Boolean = true
// String
val string: String = "Kotlin"
println("Numbers: $int, $long, $double")
println("Others: $char, $boolean, $string")
}String Operations
kotlin
fun main() {
val name = "Kotlin"
val version = 1.9
// String templates
println("Welcome to $name!")
println("Version: $version")
println("Length: ${name.length}")
// Multi-line strings
val multiline = """
|Kotlin is a modern programming language
|that makes developers happier.
|It's concise, safe, and interoperable.
""".trimMargin()
println(multiline)
// String operations
println("Uppercase: ${name.uppercase()}")
println("Contains 'lin': ${name.contains("lin")}")
println("Starts with 'Kot': ${name.startsWith("Kot")}")
}Collections
Lists
kotlin
fun main() {
// Immutable list
val readOnlyList = listOf("Apple", "Banana", "Cherry")
println("Fruits: $readOnlyList")
println("First fruit: ${readOnlyList[0]}")
println("Size: ${readOnlyList.size}")
// Mutable list
val mutableList = mutableListOf("Kotlin", "Java")
mutableList.add("Python")
mutableList.remove("Java")
println("Languages: $mutableList")
// List operations
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
val evens = numbers.filter { it % 2 == 0 }
println("Original: $numbers")
println("Doubled: $doubled")
println("Evens: $evens")
}Maps
kotlin
fun main() {
// Immutable map
val readOnlyMap = mapOf(
"name" to "Kotlin",
"version" to "1.9",
"type" to "Programming Language"
)
println("Map: $readOnlyMap")
println("Name: ${readOnlyMap["name"]}")
// Mutable map
val mutableMap = mutableMapOf<String, Int>()
mutableMap["apple"] = 5
mutableMap["banana"] = 3
mutableMap["cherry"] = 8
println("Fruit counts: $mutableMap")
// Iterate map
for ((fruit, count) in mutableMap) {
println("$fruit: $count")
}
}Functions
Basic Functions
kotlin
// Simple function
fun greet(name: String): String {
return "Hello, $name!"
}
// Single-expression function
fun add(a: Int, b: Int) = a + b
// Function with default parameters
fun greetWithDefault(name: String = "World", greeting: String = "Hello") {
println("$greeting, $name!")
}
fun main() {
println(greet("Kotlin"))
println("Sum: ${add(5, 3)}")
greetWithDefault()
greetWithDefault("Kotlin")
greetWithDefault("Kotlin", "Hi")
greetWithDefault(greeting = "Hey", name = "Developer")
}Higher-Order Functions
kotlin
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// Using lambda expressions
val doubled = numbers.map { number -> number * 2 }
val tripled = numbers.map { it * 3 } // it is default name for single-parameter lambda
println("Doubled: $doubled")
println("Tripled: $tripled")
// Custom higher-order function
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
val sum = calculate(5, 3) { a, b -> a + b }
val product = calculate(5, 3) { a, b -> a * b }
println("Sum: $sum")
println("Product: $product")
}Classes and Objects
Basic Class
kotlin
// Simple class
class Person(val name: String, var age: Int) {
fun introduce() {
println("Hi, I'm $name and I'm $age years old.")
}
fun haveBirthday() {
age++
println("Happy birthday! Now I'm $age.")
}
}
fun main() {
val person = Person("Alice", 25)
person.introduce()
person.haveBirthday()
}Data Classes
kotlin
// Data class automatically generates equals, hashCode, toString, etc.
data class User(val id: Int, val name: String, val email: String)
fun main() {
val user1 = User(1, "John", "john@example.com")
val user2 = User(1, "John", "john@example.com")
val user3 = user1.copy(name = "Jane") // Copy and modify
println("User1: $user1")
println("User1 == User2: ${user1 == user2}") // true
println("User3: $user3")
// Destructuring declaration
val (id, name, email) = user1
println("ID: $id, Name: $name, Email: $email")
}Conditional Statements
if Expression
kotlin
fun main() {
val score = 85
// if as expression
val grade = if (score >= 90) {
"A"
} else if (score >= 80) {
"B"
} else if (score >= 70) {
"C"
} else {
"F"
}
println("Score: $score, Grade: $grade")
// Simplified form
val status = if (score >= 60) "Pass" else "Fail"
println("Status: $status")
}when Expression
kotlin
fun main() {
val day = 3
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6, 7 -> "Weekend"
else -> "Invalid day"
}
println("Day $day is $dayName")
// when with ranges
val number = 15
when (number) {
in 1..10 -> println("Small number")
in 11..20 -> println("Medium number")
else -> println("Large number")
}
// when with type checking
fun describe(obj: Any): String = when (obj) {
is String -> "String of length ${obj.length}"
is Int -> "Integer: $obj"
is List<*> -> "List with ${obj.size} elements"
else -> "Unknown type"
}
println(describe("Hello"))
println(describe(42))
println(describe(listOf(1, 2, 3)))
}Loops
kotlin
fun main() {
// for loop
println("Numbers 1 to 5:")
for (i in 1..5) {
print("$i ")
}
println()
// Iterate collection
val fruits = listOf("Apple", "Banana", "Cherry")
println("Fruits:")
for (fruit in fruits) {
println("- $fruit")
}
// Iterate with index
println("Fruits with index:")
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
// while loop
var count = 0
while (count < 3) {
println("Count: $count")
count++
}
// repeat function
repeat(3) { index ->
println("Repeat $index")
}
}Extension Functions
kotlin
// Add extension function to String class
fun String.isPalindrome(): Boolean {
val cleaned = this.lowercase().replace(" ", "")
return cleaned == cleaned.reversed()
}
// Add extension function to Int class
fun Int.isEven(): Boolean = this % 2 == 0
fun main() {
val text = "A man a plan a canal Panama"
println("'$text' is palindrome: ${text.isPalindrome()}")
val number = 42
println("$number is even: ${number.isEven()}")
// Using standard library extension functions
val numbers = listOf(1, 2, 3, 4, 5)
println("Sum: ${numbers.sum()}")
println("Average: ${numbers.average()}")
println("Max: ${numbers.maxOrNull()}")
}Practical Application Example
Simple Todo List Manager
kotlin
data class Task(val id: Int, val title: String, var completed: Boolean = false)
class TodoManager {
private val tasks = mutableListOf<Task>()
private var nextId = 1
fun addTask(title: String) {
tasks.add(Task(nextId++, title))
println("Added task: $title")
}
fun completeTask(id: Int) {
tasks.find { it.id == id }?.let { task ->
task.completed = true
println("Completed task: ${task.title}")
} ?: println("Task not found")
}
fun listTasks() {
if (tasks.isEmpty()) {
println("No tasks found")
return
}
println("Tasks:")
tasks.forEach { task ->
val status = if (task.completed) "✓" else "○"
println("$status ${task.id}. ${task.title}")
}
}
fun getCompletedCount() = tasks.count { it.completed }
fun getTotalCount() = tasks.size
}
fun main() {
val todoManager = TodoManager()
// Add tasks
todoManager.addTask("Learn Kotlin basics")
todoManager.addTask("Build a simple app")
todoManager.addTask("Read Kotlin documentation")
// Display tasks
todoManager.listTasks()
// Complete tasks
todoManager.completeTask(1)
todoManager.completeTask(3)
// Display updated tasks
println("\nUpdated tasks:")
todoManager.listTasks()
// Display statistics
println("\nProgress: ${todoManager.getCompletedCount()}/${todoManager.getTotalCount()} completed")
}Common Errors and Solutions
1. Null Pointer Exception
kotlin
// Wrong way
fun badExample() {
var name: String? = null
// println(name.length) // Compile error
}
// Correct way
fun goodExample() {
var name: String? = null
// Safe call
println("Length: ${name?.length}")
// Using let
name?.let {
println("Name is not null: $it")
}
// Elvis operator
val length = name?.length ?: 0
println("Length: $length")
}2. Type Inference Issues
kotlin
fun main() {
// Ambiguous type inference
// val list = emptyList() // Compile error: cannot infer type
// Explicitly specify type
val list: List<String> = emptyList()
// Or
val list2 = emptyList<String>()
println("Lists created successfully")
}Best Practices
- Prefer val over var
- Leverage type inference, but explicitly specify types when necessary
- Use data classes to represent simple data containers
- Use extension functions to enhance existing class functionality
- Use when expressions instead of complex if-else chains
Next Steps
Now that you've quickly learned Kotlin's core features, let's dive deeper into Kotlin's basic syntax rules.
Next Chapter: Basic Syntax
Exercises
- Create a simple calculator program supporting add, subtract, multiply, divide operations
- Implement a student grade management system with student information and grade calculation
- Write a function to check if a string is a palindrome
- Create a shopping cart class supporting add item, remove item, and calculate total price
- Use extension functions to add a method for List to find the index of maximum value