In the previous tutorial, you learned what Kotlin is and why developers love it. Now it is time to install Kotlin on your computer and write your first program.
In this tutorial, you will:
- Install IntelliJ IDEA (the best IDE for Kotlin)
- Create a Kotlin project
- Write and run your first programs
- Try the Kotlin REPL
- Use the Kotlin Playground (no installation needed)
Option 1: Kotlin Playground (No Installation)
If you want to try Kotlin right now without installing anything, go to the Kotlin Playground.
The Playground is a website where you can write and run Kotlin code in your browser. It is perfect for quick experiments and for following this tutorial series.
Type this code and click “Run”:
fun main() {
println("Hello, World!")
}
You should see “Hello, World!” in the output. That’s it. Your first Kotlin program.
The Playground is great for learning, but for real projects, you need a proper IDE. Let’s install one.
Option 2: Install IntelliJ IDEA
IntelliJ IDEA is the best IDE for Kotlin. This makes sense because JetBrains created both Kotlin and IntelliJ.
Step 1: Download IntelliJ IDEA
Go to jetbrains.com/idea/download and download IntelliJ IDEA Community Edition. It is free and has everything you need for Kotlin development.
- Windows: Download the
.exeinstaller and run it - macOS: Download the
.dmgfile, open it, and drag IntelliJ to your Applications folder - Linux: Download the
.tar.gz, extract it, and runbin/idea.sh
Step 2: Create a New Kotlin Project
- Open IntelliJ IDEA
- Click New Project
- Set these options:
- Name:
kotlin-tutorial - Language: Kotlin
- Build system: Gradle
- JDK: Download a JDK if you don’t have one (IntelliJ can do this for you — select “Download JDK” from the dropdown)
- Gradle DSL: Kotlin
- Name:
- Click Create
IntelliJ will create the project and download all dependencies. This takes a minute the first time.
Step 3: Find the Main File
After the project is created, look at the left panel (Project view). Navigate to:
src/main/kotlin/Main.kt
You should see a file with this code:
fun main() {
println("Hello World!")
}
Step 4: Run Your First Program
There are three ways to run the program:
- Green arrow: Click the green play button next to the
mainfunction - Keyboard shortcut: Press
Ctrl+Shift+F10(Windows/Linux) orControl+Shift+R(macOS) - Menu: Right-click the file and select “Run ‘MainKt’”
You should see “Hello World!” in the Run panel at the bottom.
Congratulations. You just ran your first Kotlin program.
Option 3: Command Line Installation
If you prefer the command line over an IDE, you can install the Kotlin compiler directly.
macOS (using Homebrew)
brew install kotlin
Linux (using SDKMAN)
curl -s "https://get.sdkman.io" | bash
sdk install kotlin
Windows (using Scoop)
scoop install kotlin
Verify Installation
After installation, check that Kotlin is available:
kotlin -version
You should see something like:
Kotlin version 2.3.0-release-xxx
Run from Command Line
Create a file called hello.kt:
fun main() {
println("Hello from the command line!")
}
Compile and run it:
kotlinc hello.kt -include-runtime -d hello.jar
java -jar hello.jar
Or run it directly without creating a JAR:
kotlin hello.kt
The Kotlin REPL
REPL stands for Read-Eval-Print-Loop. It is an interactive mode where you type Kotlin code and see the result immediately.
Start the REPL
In IntelliJ IDEA:
- Go to Tools > Kotlin > Kotlin REPL
- A REPL panel opens at the bottom
From the command line:
kotlinc
Try the REPL
Type these lines one at a time and press Ctrl+Enter (or Enter in the command line REPL):
val name = "Alex"
println("Hello, $name!")
2 + 3
10 * 5
"Kotlin".length
The REPL shows the result of each expression immediately. It is great for testing small pieces of code.
Type :quit to exit the command line REPL.
Your First Programs
Now let’s write some real programs. Create a new Kotlin file in your project or use the Playground.
Program 1: Hello World
fun main() {
println("Hello, World!")
print("Hello, ")
println("Kotlin!")
}
Output:
Hello, World!
Hello, Kotlin!
println() prints text and moves to the next line. print() prints text but stays on the same line.
Program 2: User Information
fun printUserInfo(name: String, age: Int) {
println("Name: $name")
println("Age: $age")
println("Birth year: approximately ${java.time.Year.now().value - age}")
println("---")
}
fun main() {
printUserInfo("Alex", 25)
printUserInfo("Sam", 30)
}
Output:
Name: Alex
Age: 25
Birth year: approximately 2001
---
Name: Sam
Age: 30
Birth year: approximately 1996
---
Here you see:
- Functions use the
funkeyword - Parameters have a name and a type:
name: String - String templates use
$variableor${expression}
Program 3: Simple Calculator
fun simpleCalculator(a: Int, b: Int) {
println("a = $a, b = $b")
println("$a + $b = ${a + b}")
println("$a - $b = ${a - b}")
println("$a * $b = ${a * b}")
println("$a / $b = ${a / b}") // Integer division — no decimals
println("$a % $b = ${a % b}") // Remainder (modulo)
// For decimal results, convert to Double
println("$a / $b (decimal) = ${a.toDouble() / b}")
}
fun main() {
simpleCalculator(10, 3)
}
Output:
a = 10, b = 3
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3
10 % 3 = 1
10 / 3 (decimal) = 3.3333333333333335
Notice that 10 / 3 gives 3, not 3.33. When you divide two integers, Kotlin gives you an integer result. To get decimals, convert one number to Double with toDouble().
Program 4: String Operations
fun main() {
val greeting = "Hello, Kotlin!"
println("Original: $greeting")
println("Length: ${greeting.length}")
println("Uppercase: ${greeting.uppercase()}")
println("Lowercase: ${greeting.lowercase()}")
println("First char: ${greeting.first()}")
println("Last char: ${greeting.last()}")
println("Contains 'Kotlin': ${greeting.contains("Kotlin")}")
println("Replace: ${greeting.replace("Kotlin", "World")}")
// Multi-line strings use triple quotes
val multiLine = """
This is a
multi-line
string in Kotlin
""".trimIndent()
println(multiLine)
}
Strings in Kotlin have many useful built-in functions. You don’t need to import anything. They are always available.
The triple-quoted string """...""" lets you write text on multiple lines. trimIndent() removes the common whitespace from the beginning of each line.
Program 5: Working with Numbers
fun main() {
val intNumber = 42
val longNumber = 1_000_000_000L // L suffix for Long
val doubleNumber = 3.14159
val floatNumber = 2.5f // f suffix for Float
println("Int: $intNumber")
println("Long: $longNumber")
println("Double: $doubleNumber")
println("Float: $floatNumber")
// Number conversions
val intToDouble: Double = intNumber.toDouble()
val doubleToInt: Int = doubleNumber.toInt()
println("Int to Double: $intToDouble")
println("Double to Int: $doubleToInt") // 3, not 3.14
// Useful math
println("Max of 10 and 20: ${maxOf(10, 20)}")
println("Min of 10 and 20: ${minOf(10, 20)}")
}
Important things about numbers in Kotlin:
- You can use underscores in numbers for readability:
1_000_000 - Kotlin does not convert number types automatically. You must use
toDouble(),toInt(), etc. toInt()truncates (cuts off decimals). It does not round.
Program 6: Different Print Styles
fun main() {
// println — with a new line
println("This is println")
// print — no new line
print("This is ")
print("print ")
println("(no new line between words)")
// String templates
val language = "Kotlin"
val version = 2.3
println("Language: $language, Version: $version")
// Formatted output
val pi = 3.14159265
println("Pi with 2 decimals: ${"%.2f".format(pi)}")
println("Pi with 4 decimals: ${"%.4f".format(pi)}")
}
For formatted numbers, you can use "%.2f".format(number) where 2 is the number of decimal places.
Common Errors and How to Fix Them
Error: “Unresolved reference”
fun main() {
println(name) // Error: Unresolved reference: name
}
Fix: You used a variable that does not exist. Declare it first with val or var.
Error: “Type mismatch”
fun main() {
val age: Int = "25" // Error: Type mismatch
}
Fix: You tried to put a String where an Int is expected. Use "25".toInt() to convert.
Error: “A ‘return’ expression required in a body”
fun add(a: Int, b: Int): Int {
a + b // Error: needs return
}
Fix: Add return before the expression: return a + b.
Project Structure
When you create a Kotlin project with Gradle, the structure looks like this:
kotlin-tutorial/
├── build.gradle.kts # Build configuration
├── settings.gradle.kts # Project settings
├── gradlew # Gradle wrapper (Linux/macOS)
├── gradlew.bat # Gradle wrapper (Windows)
├── gradle/ # Gradle files
└── src/
├── main/
│ └── kotlin/ # Your Kotlin source files
│ └── com/kemalcodes/tutorial/
│ └── Main.kt
└── test/
└── kotlin/ # Your test files
- src/main/kotlin/ — Your main code goes here
- src/test/kotlin/ — Your test code goes here
- build.gradle.kts — Tells Gradle how to build your project
Building with Gradle
Gradle is the build tool that compiles and runs your project. Here are the commands you need:
# Build the project (compile all code)
./gradlew build
# Run the main function
./gradlew run
# Run tests
./gradlew test
# Clean build files
./gradlew clean
On Windows, use gradlew.bat instead of ./gradlew.
Source Code
You can find the complete source code for this tutorial on GitHub:
What’s Next?
In the next tutorial, Kotlin Tutorial #3: Variables, Types, and Type Inference, you will learn:
- The difference between
valandvar - All basic types in Kotlin (Int, Double, String, Boolean, and more)
- How type inference works
- Type conversions
- Constants with
const val
This is part 2 of the Kotlin Tutorial series. Check out Part 1: What is Kotlin? if you missed it. Need a quick reference? See the Kotlin Cheat Sheet.