Skip to main content

Kotlin Introduction

What is Kotlin?

Kotlin logo

Kotlin is a modern, statically typed programming language that runs on the Java Virtual Machine (JVM). Developed by JetBrains (the company behind popular IDEs like IntelliJ IDEA), Kotlin was officially announced in 2011 and reached version 1.0 in 2016. In 2017, Google announced first-class support for Kotlin on Android, making it an official language for Android development.

Kotlin combines object-oriented and functional programming features, offering a more concise, safer, and more expressive alternative to Java while maintaining full interoperability with Java code.

Why Learn Kotlin?

There are several compelling reasons to learn Kotlin:

  1. Android Development: Kotlin is now the preferred language for Android app development.

  2. Concise Syntax: Kotlin reduces boilerplate code significantly compared to Java.

  3. Safety Features: Null safety is built into the type system, helping eliminate NullPointerExceptions.

  4. Interoperability: Kotlin works seamlessly with existing Java code and libraries.

  5. Modern Features: Kotlin includes modern programming features like lambda expressions, extension functions, and coroutines.

  6. Versatility: You can use Kotlin for Android, server-side, web development, and even native applications.

Setting Up Kotlin

Before we dive into coding, let's set up a Kotlin development environment.

Online Playground

The quickest way to start experimenting with Kotlin is through the Kotlin Playground, an online editor that allows you to write and run Kotlin code directly in your browser.

Local Setup

For a local development environment, you have several options:

  1. IntelliJ IDEA: Download the Community Edition (free) or Ultimate Edition from JetBrains website.

  2. Android Studio: If you're interested in Android development, Android Studio comes with Kotlin support.

  3. Command Line: Install the Kotlin compiler following the official documentation.

Your First Kotlin Program

Let's start with the traditional "Hello, World!" program:

kotlin
fun main() {
println("Hello, World!")
}

When you run this code, you'll see:

Hello, World!

Let's break down what's happening:

  • fun is the keyword used to declare a function in Kotlin.
  • main() is the entry point of a Kotlin program.
  • println() is a built-in function that prints text to the console followed by a line break.

Basic Syntax

Variables

Kotlin has two main types of variables:

  1. Read-only variables (declared with val)
  2. Mutable variables (declared with var)
kotlin
fun main() {
val name = "John" // Read-only (cannot be reassigned)
var age = 25 // Mutable (can be changed)

// age = 26 // This is valid
// name = "Jane" // This would cause an error

println("Name: $name, Age: $age")
}

Output:

Name: John, Age: 25

Type Inference and Explicit Types

Kotlin can infer types automatically, but you can also specify them explicitly:

kotlin
fun main() {
val implicitInt = 42 // Type is inferred as Int
val explicitInt: Int = 42 // Type is explicitly declared

val implicitDouble = 3.14 // Type is inferred as Double
val explicitDouble: Double = 3.14

println("Implicit Int: $implicitInt, Explicit Int: $explicitInt")
println("Implicit Double: $implicitDouble, Explicit Double: $explicitDouble")
}

Output:

Implicit Int: 42, Explicit Int: 42
Implicit Double: 3.14, Explicit Double: 3.14

Basic Data Types

Kotlin provides several basic data types:

kotlin
fun main() {
val myInt: Int = 100
val myLong: Long = 1234567890L
val myDouble: Double = 3.14
val myFloat: Float = 2.71f
val myBoolean: Boolean = true
val myChar: Char = 'A'
val myString: String = "Hello Kotlin"

println("Integer: $myInt")
println("Long: $myLong")
println("Double: $myDouble")
println("Float: $myFloat")
println("Boolean: $myBoolean")
println("Character: $myChar")
println("String: $myString")
}

String Templates

As you've seen in the previous examples, Kotlin allows for string interpolation using the $ symbol:

kotlin
fun main() {
val name = "Alice"
val age = 30

// Simple variable reference
println("Hello, $name!")

// Expression in string template
println("Next year, you will be ${age + 1} years old.")

// Accessing properties
println("Your name has ${name.length} characters.")
}

Output:

Hello, Alice!
Next year, you will be 31 years old.
Your name has 5 characters.

Control Flow

Conditional Expressions

Kotlin uses if, when, for, and while for control flow.

If Expression

In Kotlin, if is an expression (returns a value) rather than just a statement:

kotlin
fun main() {
val number = 42

// Traditional usage
if (number > 0) {
println("Positive number")
} else if (number < 0) {
println("Negative number")
} else {
println("Zero")
}

// Using if as an expression
val result = if (number % 2 == 0) "Even" else "Odd"
println("The number is $result")
}

Output:

Positive number
The number is Even

When Expression

The when expression is Kotlin's replacement for the switch statement in other languages, but more powerful:

kotlin
fun main() {
val day = 3

val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}

println("Day $day is $dayName")
}

Output:

Day 3 is Wednesday

Loops

For Loop

kotlin
fun main() {
// Loop through a range
println("Counting from 1 to 5:")
for (i in 1..5) {
println(i)
}

// Loop through an array
println("\nFruits:")
val fruits = arrayOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
println(fruit)
}

// Loop with index
println("\nIndexed fruits:")
for ((index, fruit) in fruits.withIndex()) {
println("$index: $fruit")
}
}

Output:

Counting from 1 to 5:
1
2
3
4
5

Fruits:
Apple
Banana
Cherry

Indexed fruits:
0: Apple
1: Banana
2: Cherry

While and Do-While Loops

kotlin
fun main() {
// While loop
var counter = 0
println("While loop:")
while (counter < 3) {
println("Counter: $counter")
counter++
}

// Do-while loop
counter = 0
println("\nDo-while loop:")
do {
println("Counter: $counter")
counter++
} while (counter < 3)
}

Output:

While loop:
Counter: 0
Counter: 1
Counter: 2

Do-while loop:
Counter: 0
Counter: 1
Counter: 2

Functions

Functions in Kotlin are declared using the fun keyword:

kotlin
fun main() {
// Call function without parameters
greet()

// Call function with parameters
greetPerson("Alice")

// Function with return value
val sum = add(5, 7)
println("5 + 7 = $sum")

// Single-expression function
val product = multiply(4, 3)
println("4 * 3 = $product")
}

// Function with no parameters and no return value
fun greet() {
println("Hello, world!")
}

// Function with parameter
fun greetPerson(name: String) {
println("Hello, $name!")
}

// Function with parameters and return value
fun add(a: Int, b: Int): Int {
return a + b
}

// Single-expression function
fun multiply(a: Int, b: Int): Int = a * b

Output:

Hello, world!
Hello, Alice!
5 + 7 = 12
4 * 3 = 12

Real-World Example: Simple Temperature Converter

Let's create a practical example that converts temperatures between Celsius and Fahrenheit:

kotlin
fun main() {
println("Temperature Converter")
println("=====================")

val celsiusTemperatures = listOf(0, 25, 100)

println("Celsius to Fahrenheit:")
for (celsius in celsiusTemperatures) {
val fahrenheit = celsiusToFahrenheit(celsius)
println("$celsius°C = $fahrenheit°F")
}

println("\nFahrenheit to Celsius:")
val fahrenheitTemperatures = listOf(32, 77, 212)
for (fahrenheit in fahrenheitTemperatures) {
val celsius = fahrenheitToCelsius(fahrenheit)
println("$fahrenheit°F = $celsius°C")
}
}

// Convert Celsius to Fahrenheit
fun celsiusToFahrenheit(celsius: Int): Double {
return celsius * 9.0 / 5.0 + 32.0
}

// Convert Fahrenheit to Celsius
fun fahrenheitToCelsius(fahrenheit: Int): Double {
return (fahrenheit - 32.0) * 5.0 / 9.0
}

Output:

Temperature Converter
=====================
Celsius to Fahrenheit:
0°C = 32.0°F
25°C = 77.0°F
100°C = 212.0°F

Fahrenheit to Celsius:
32°F = 0.0°C
77°F = 25.0°C
212°F = 100.0°C

This example demonstrates:

  • Function definitions with parameters and return values
  • List creation and iteration
  • String templates for formatted output
  • Mathematical operations

Summary

In this introduction to Kotlin, we've covered:

  • What Kotlin is and why it's worth learning
  • How to set up a Kotlin development environment
  • Basic syntax including variables, data types, and string templates
  • Control flow statements like if, when, and loops
  • Function declarations and usage
  • A practical example with temperature conversion

Kotlin's modern features, safety guarantees, and concise syntax make it an excellent choice for both beginners and experienced programmers.

Additional Resources

If you want to learn more about Kotlin, check out these resources:

Exercises

To solidify your understanding, try these exercises:

  1. Write a program that checks if a number is prime.
  2. Create a function that reverses a string.
  3. Implement a simple calculator that can add, subtract, multiply, and divide.
  4. Write a program that converts a decimal number to binary.
  5. Create a function that calculates the factorial of a number.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)