Complete Kotlin Tutorial: From Setup to Functions
Table of Contents
1. Introduction to Kotlin and Use Cases
What is Kotlin?
Kotlin is a modern, statically-typed programming language developed by JetBrains. It's designed to be fully interoperable with Java while providing more concise syntax and enhanced safety features.
Key Features
- Concise: Drastically reduces boilerplate code
- Safe: Null safety built into the type system
- Interoperable: 100% compatible with Java
- Tool-friendly: Works with existing Java tools and frameworks
Primary Use Cases
1. Android Development
- Primary language for Android app development (Google's preferred choice)
- Replaces Java for new Android projects
- Better performance and fewer crashes
2. Server-Side Development
- Web applications using frameworks like Ktor or Spring Boot
- Microservices and REST APIs
- Enterprise applications
3. Desktop Applications
- Cross-platform desktop apps using Compose for Desktop
- JavaFX applications
4. Multiplatform Development
- Share code between Android, iOS, web, and desktop
- Kotlin Multiplatform Mobile (KMM)
2. Setting up Kotlin Development Environment
Option 1: IntelliJ IDEA (Recommended for General Kotlin Development)
Step 1: Download and Install
- Visit JetBrains IntelliJ IDEA
- Download Community Edition (free) or Ultimate Edition
- Install following the setup wizard
Step 2: Create a New Kotlin Project
- Open IntelliJ IDEA
- Click "New Project"
- Select "Kotlin" from the left panel
- Choose "Console Application"
- Configure project settings:
- Project Name: KotlinTutorial
- Location: Choose your preferred directory
- Language: Kotlin
- Build System: Gradle Kotlin DSL (recommended)
- Project Name:
- Click "Create"
Step 3: Verify Setup
Create a simple "Hello World" program:
fun main() { println("Hello, Kotlin World!") }
Option 2: Android Studio (For Android Development)
Step 1: Download and Install
- Visit Android Studio
- Download and install following the setup wizard
- Complete the initial setup including SDK downloads
Step 2: Create New Project
- Open Android Studio
- Click "Create New Project"
- Select "Empty Activity"
- Configure your project:
- Name: KotlinAndroidTutorial
- Language: Kotlin
- API Level: Choose latest stable version
- Name:
- Click "Finish"
Option 3: Online Kotlin Playground (For Quick Testing)
- Visit Kotlin Playground
- No installation required
- Perfect for testing small code snippets
3. Variables and Data Types
Variable Declarations
Kotlin uses two keywords for variable declaration:
val - Immutable (Read-only)
val name = "John" // Type inferred as String val age: Int = 25 // Explicit type declaration val pi = 3.14159 // Type inferred as Double // name = "Jane" // Error! Cannot reassign val
var - Mutable
var score = 100 // Type inferred as Int var temperature: Double = 98.6 var isActive = true score = 150 // OK! Can reassign var temperature = 99.1 // OK!
Basic Data Types
Numeric Types
// Integer types val byteValue: Byte = 127 // 8-bit val shortValue: Short = 32767 // 16-bit val intValue: Int = 2147483647 // 32-bit val longValue: Long = 9223372036854775807L // 64-bit // Floating-point types val floatValue: Float = 3.14f // 32-bit val doubleValue: Double = 3.14159 // 64-bit (default for decimals) // Numeric operations val sum = 10 + 5 val difference = 20 - 8 val product = 4 * 7 val quotient = 15 / 3 val remainder = 17 % 5 println("Sum: $sum, Difference: $difference, Product: $product")
Character and String Types
// Character val grade: Char = 'A' val symbol = '@' // String val firstName = "Alice" val lastName = "Johnson" val fullName = firstName + " " + lastName // Multi-line strings val address = """ 123 Main Street Anytown, ST 12345 United States """.trimIndent() println("Full name: $fullName") println("Address:\n$address")
Boolean Type
val isStudent = true val isEmployed = false val hasLicense = true val canDrive = hasLicense && !isStudent println("Can drive: $canDrive")
Nullable Types
// Non-nullable (default) var nonNullString: String = "Hello" // nonNullString = null // Compilation error! // Nullable var nullableString: String? = "Hello" nullableString = null // OK! // Safe calls val length = nullableString?.length // Returns null if nullableString is null println("Length: $length") // Elvis operator val safeLength = nullableString?.length ?: 0 println("Safe length: $safeLength")
Type Conversion
val intNumber = 42 val longNumber = intNumber.toLong() val doubleNumber = intNumber.toDouble() val stringNumber = intNumber.toString() println("Int: $intNumber, Long: $longNumber, Double: $doubleNumber, String: $stringNumber") // Parsing strings to numbers val userInput = "123" val parsedInt = userInput.toInt() val parsedDouble = userInput.toDouble()
4. Conditionals and Loops
Conditional Statements
if Expressions
val temperature = 75 // Traditional if-else if (temperature > 80) { println("It's hot!") } else if (temperature > 60) { println("It's warm!") } else { println("It's cold!") } // if as expression (returns value) val weather = if (temperature > 80) "hot" else if (temperature > 60) "warm" else "cold" println("Weather is $weather") // Single line if val status = if (temperature > 70) "comfortable" else "uncomfortable"
when Expression (Similar to switch)
val dayOfWeek = 3 when (dayOfWeek) { 1 -> println("Monday") 2 -> println("Tuesday") 3 -> println("Wednesday") 4 -> println("Thursday") 5 -> println("Friday") 6, 7 -> println("Weekend!") else -> println("Invalid day") } // when as expression val dayName = when (dayOfWeek) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6, 7 -> "Weekend" else -> "Unknown" } // when with ranges and conditions val score = 85 val grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" in 60..69 -> "D" else -> "F" } println("Score: $score, Grade: $grade")
Loops
for Loops
// Range loops println("Counting 1 to 5:") for (i in 1..5) { println(i) } println("\nCounting 1 to 10 by 2s:") for (i in 1..10 step 2) { println(i) } println("\nCountdown from 5 to 1:") for (i in 5 downTo 1) { println(i) } // Iterating over collections val fruits = listOf("apple", "banana", "orange", "grape") println("\nFruits:") for (fruit in fruits) { println("- $fruit") } // With index println("\nFruits with index:") for ((index, fruit) in fruits.withIndex()) { println("$index: $fruit") }
while and do-while Loops
// while loop var counter = 1 println("While loop:") while (counter <= 5) { println("Counter: $counter") counter++ } // do-while loop var number = 1 println("\nDo-while loop:") do { println("Number: $number") number++ } while (number <= 3)
Loop Control
// break and continue println("Numbers 1-10, skipping 5:") for (i in 1..10) { if (i == 5) { continue // Skip 5 } if (i == 8) { break // Stop at 8 } println(i) }
5. Functions and String Templates
Function Basics
Simple Functions
// Basic function fun greet() { println("Hello, World!") } // Function with parameters fun greetUser(name: String) { println("Hello, $name!") } // Function with return value fun add(a: Int, b: Int): Int { return a + b } // Single expression function fun multiply(a: Int, b: Int): Int = a * b // Function with default parameters fun introduce(name: String, age: Int = 25, city: String = "Unknown") { println("Hi, I'm $name, $age years old, from $city") } // Using functions greet() greetUser("Alice") val result = add(5, 3) println("5 + 3 = $result") val product = multiply(4, 7) println("4 * 7 = $product") introduce("Bob") introduce("Carol", 30) introduce("Dave", 35, "New York")
Functions with Named Arguments
fun createUser(name: String, email: String, age: Int, isActive: Boolean = true) { println("User: $name ($email), Age: $age, Active: $isActive") } // Using named arguments createUser( name = "John", email = "john@example.com", age = 28 ) createUser( email = "jane@example.com", name = "Jane", // Order doesn't matter with named arguments age = 32, isActive = false )
Higher-Order Functions
// Function that takes another function as parameter fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int { return operation(a, b) } // Using higher-order functions val sum = calculate(10, 5) { x, y -> x + y } val difference = calculate(10, 5) { x, y -> x - y } val product = calculate(10, 5) { x, y -> x * y } println("Sum: $sum, Difference: $difference, Product: $product")
String Templates
Basic String Interpolation
val name = "Alice" val age = 30 val city = "Boston" // Simple variable interpolation println("My name is $name") // Expression in templates println("Next year I'll be ${age + 1} years old") // Complex expressions val fullInfo = "I'm $name, ${age} years old, living in ${city.uppercase()}" println(fullInfo)
Advanced String Templates
val price = 29.99 val quantity = 3 val tax = 0.08 // Calculations in templates val total = "Total: $${String.format("%.2f", (price * quantity) * (1 + tax))}" println(total) // Function calls in templates fun formatCurrency(amount: Double): String = "$%.2f".format(amount) val invoice = """ Invoice Details: - Item Price: ${formatCurrency(price)} - Quantity: $quantity - Subtotal: ${formatCurrency(price * quantity)} - Tax (${(tax * 100).toInt()}%): ${formatCurrency(price * quantity * tax)} - Total: ${formatCurrency(price * quantity * (1 + tax))} """.trimIndent() println(invoice)
Raw Strings and Templates
val path = "C:\\Users\\John\\Documents" val url = "https://example.com/api/users" // Raw string (triple quotes) with templates val config = """ { "user": "$name", "age": $age, "path": "$path", "api_url": "$url" } """.trimIndent() println("Configuration:") println(config)
6. Practice Exercises
Exercise 1: Personal Information System
Create a program that manages personal information:
fun main() { // Create variables for personal info val firstName = "John" val lastName = "Doe" var age = 25 val isStudent = false val gpa: Double? = null // null because not a student // Use string templates to display info println("=== Personal Information ===") println("Name: $firstName $lastName") println("Age: $age") println("Student Status: ${if (isStudent) "Student" else "Not a Student"}") println("GPA: ${gpa ?: "N/A"}") // Simulate birthday age++ println("\nAfter birthday: $age years old") }
Exercise 2: Grade Calculator
fun calculateGrade(score: Int): String { return when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" in 60..69 -> "D" else -> "F" } } fun main() { val scores = listOf(95, 87, 76, 64, 58) println("=== Grade Report ===") for ((index, score) in scores.withIndex()) { val grade = calculateGrade(score) println("Student ${index + 1}: Score $score = Grade $grade") } val average = scores.sum() / scores.size println("\nClass Average: $average (${calculateGrade(average)})") }
Exercise 3: Simple Calculator
fun add(a: Double, b: Double): Double = a + b fun subtract(a: Double, b: Double): Double = a - b fun multiply(a: Double, b: Double): Double = a * b fun divide(a: Double, b: Double): Double = if (b != 0.0) a / b else 0.0 fun calculator(num1: Double, num2: Double, operation: String): String { val result = when (operation.lowercase()) { "add", "+" -> add(num1, num2) "subtract", "-" -> subtract(num1, num2) "multiply", "*" -> multiply(num1, num2) "divide", "/" -> divide(num1, num2) else -> { return "Invalid operation: $operation" } } return "$num1 $operation $num2 = $result" } fun main() { val operations = listOf("+", "-", "*", "/") val num1 = 15.0 val num2 = 4.0 println("=== Calculator Results ===") for (op in operations) { println(calculator(num1, num2, op)) } }
Exercise 4: Number Guessing Game Logic
fun checkGuess(guess: Int, target: Int): String { return when { guess == target -> "Correct! You guessed it!" guess < target -> "Too low! Try higher." else -> "Too high! Try lower." } } fun main() { val targetNumber = 42 val guesses = listOf(30, 50, 40, 45, 42) println("=== Number Guessing Game ===") println("Target number is $targetNumber") for ((attempt, guess) in guesses.withIndex()) { val feedback = checkGuess(guess, targetNumber) println("Attempt ${attempt + 1}: Guess $guess - $feedback") if (guess == targetNumber) { println("Game won in ${attempt + 1} attempts!") break } } }
Summary
You've now learned the fundamental concepts of Kotlin programming:
- Setup: How to configure IntelliJ IDEA or Android Studio for Kotlin development
- Variables: The difference between valandvar, and various data types
- Conditionals: Using ifexpressions andwhenstatements for decision making
- Loops: Iterating with for,while, anddo-whileloops
- Functions: Creating reusable code blocks with parameters and return values
- String Templates: Embedding expressions and variables in strings
Next Steps
- Explore object-oriented programming with classes and objects
- Learn about collections (List, Set, Map) and their operations
- Dive into advanced features like lambdas, extension functions, and coroutines
- Start building real applications with these fundamentals
Practice these concepts by creating small programs and gradually building more complex applications. The best way to learn programming is by writing code!