Learn Kotlin · 1/18

Welcome to Kotlin: Setup and First Steps

7 min read

Welcome, future Kotlin developer! Get ready to dive into a language that's not only powerful and modern but also a joy to write. This guide will walk you through the absolute essentials to get you from zero to coding in Kotlin.


1. The 'Why': Motivation and Kotlin's Superpowers ✨

The Problem: Imagine you're building a complex application. Your code is getting long and repetitive, and you're constantly worried about errors that crash your program, especially those sneaky "null pointer exceptions" that are the bane of many developers. You need a language that is clear, concise, and safe.

The Solution: Kotlin!

Kotlin emerged to tackle these very problems. It's a modern programming language developed by JetBrains (the brilliant minds behind many popular developer tools) that runs on the Java Virtual Machine (JVM). Think of it as a supercharged version of Java that's more expressive, safer, and a lot more fun to use.

Kotlin's Superpowers:

  • 100% Interoperable with Java: This is a huge deal! It means you can have both Kotlin and Java code in the same project, and they'll work together seamlessly. You can call Java code from Kotlin and vice versa. This makes it incredibly easy for existing Java projects to start adopting Kotlin gradually. It's like having a universal translator for two closely related languages. 🤝

  • Concise and Expressive: Kotlin allows you to write more with less code. This doesn't just mean less typing; it means your code becomes more readable and easier to understand.

    Imagine you need to create a simple data-holding class in Java:

    java
    public class Customer {
        private final String name;
        private final String email;
    
        public Customer(String name, String email) {
            this.name = name;
            this.email = email;
        }
    
        public String getName() {
            return name;
        }
    
        public String getEmail() {
            return email;
        }
        // ... plus equals(), hashCode(), and toString()
    }

    Here's the equivalent in Kotlin:

    kotlin
    data class Customer(val name: String, val email: String)

    Yes, that's it! Kotlin automatically generates all the boilerplate for you.

  • Null Safety: One of the most common and frustrating bugs in programming is the "Null Pointer Exception" (NPE). It happens when you try to use something that hasn't been assigned a value (it's "null"). Kotlin's type system is designed to eliminate this problem from your code. 🛡️ By default, variables in Kotlin cannot hold null values. If you need to allow nulls, you have to explicitly declare it, and the compiler will force you to handle it safely.

    kotlin
    var name: String = "John Doe"
    // name = null // This would cause a compilation error!
    
    var address: String? = "123 Main St" // The '?' allows this variable to hold null
    address = null // This is perfectly fine
  • Modern and Feature-Rich: Kotlin is packed with modern programming features like smart casts, extension functions, and coroutines for asynchronous programming, making your development process smoother and more efficient.

Fun Fact: Kotlin is named after an island near St. Petersburg, Russia, just like Java is named after an island in Indonesia. The JetBrains team who created Kotlin has a large office in St. Petersburg! 🏝️


2. Environment Setup: Installing the JDK and IntelliJ IDEA 🛠️

To start writing Kotlin code, you need two main things: the Java Development Kit (JDK) to run your code on the JVM, and an Integrated Development Environment (IDE) to write and manage your code. We'll be using IntelliJ IDEA, which is also made by JetBrains and has the best Kotlin support out there.

Step 1: Install the JDK (Java Development Kit)

The JDK is the engine that will compile and run your Kotlin code.

  1. Download: Head over to the official Oracle JDK download page or consider alternatives like AdoptOpenJDK. A recent LTS (Long-Term Support) version like JDK 17 or JDK 21 is a great choice.
  2. Installation:
    • Windows: Run the downloaded .exe installer and follow the on-screen instructions. It's a standard installation wizard.
    • macOS: Open the downloaded .dmg file and follow the installer prompts.
    • Linux: The installation process can vary depending on your distribution. You can often use a package manager like apt or yum. For example, on Ubuntu, you might run sudo apt-get install openjdk-17-jdk.
  3. Verify Installation: Open a new terminal or command prompt and type:
    bash
    java -version
    If you see output displaying the Java version you just installed, you're good to go!

Step 2: Install IntelliJ IDEA

IntelliJ IDEA is the premier IDE for Kotlin development.

  1. Download: Go to the JetBrains IntelliJ IDEA download page. The free "Community" edition has everything you need to get started with Kotlin.
  2. Installation:
    • Windows: Run the .exe installer. You can generally accept the default settings.
    • macOS: Drag the IntelliJ IDEA app from the downloaded .dmg file into your Applications folder.
    • Linux: Unpack the .tar.gz file and run the idea.sh script from the bin directory.

IntelliJ IDEA comes with the Kotlin plugin bundled, so you don't need to install anything extra for Kotlin support.


3. Your First Kotlin Program: 'Hello World' 👋

It's a tradition in programming to start with a "Hello, World!" application. Let's create one.

  1. Create a New Project:

    • Open IntelliJ IDEA.
    • Click on New Project.
    • In the left-hand menu, select Kotlin.
    • Give your project a name (e.g., "HelloWorld").
    • Ensure that the Project SDK (or JDK) is set to the JDK you installed earlier.
    • Click Create.
  2. Create a Kotlin File:

    • In the Project view on the left, right-click on the src folder.
    • Go to New -> Kotlin File/Class.
    • Give your file a name, for example, Main. You can just create a "File".
  3. Write the Code:

    • Inside your Main.kt file, type the following code:
    kotlin
    fun main() {
        println("Hello, World!")
    }

    Let's quickly break this down:

    • fun: This is the keyword in Kotlin to declare a function.
    • main: This is the special name for the function that serves as the entry point of our program. When you run the application, the code inside the main function is the first to be executed.
    • (): These parentheses are for any parameters (inputs) the function might take. Our main function doesn't need any for now.
    • {}: These curly braces define the body of the function. All the code for this function goes inside them.
    • println("Hello, World!"): This is a standard Kotlin function that prints a line of text to the console.
  4. Run Your Program:

    • You'll see a green "play" button in the gutter next to your main function. Click it!
    • Select "Run 'MainKt'".
    • You should see "Hello, World!" printed in the Run window at the bottom of your IDE.

Congratulations, you've just written and executed your first Kotlin program! 🎉


4. Playground and REPL: Testing Code Quickly 🧪

Sometimes you just want to test a small snippet of code without creating a whole new project. Kotlin provides excellent tools for this.

Kotlin Playground

This is an online tool where you can write and run Kotlin code directly in your browser. It's perfect for quick experiments and sharing code.

IntelliJ Kotlin REPL (Read-Eval-Print Loop)

The REPL is an interactive shell for trying out Kotlin code directly within your IDE.

  1. How to open it: In IntelliJ IDEA, go to Tools -> Kotlin -> Kotlin REPL.

  2. How to use it: A new window will open. You can type any Kotlin expression and press Ctrl+Enter (or Cmd+Enter on Mac) to execute it immediately. The result will be shown on the next line.

    Try typing these lines one by one and executing them:

    kotlin
    val message = "This is a test"
    println(message)
    10 + 5

You'll see the output instantly. The REPL is fantastic for learning new concepts and quickly checking how a function works without the ceremony of a full program.


Extra Reading & References 📚

Challenge

Your task is to write a Kotlin program that defines a user profile and prints a welcome message.

Requirements:

  1. Define a data class named User.
  2. The User class must contain the following three properties in this exact order:
    • name: a non-nullable String.
    • id: an Int.
    • nickname: a nullable String.
  3. Inside the main function, create an instance of the User class.
    • Initialize name with the value "Alex".
    • Initialize id with the value 1.
    • Initialize nickname with null.
  4. Using the properties from the instance you created, print the following exact string: Welcome, Alex! Your ID is 1.

Expected result

Your code should correctly define a data class named User with the specified properties and types. The main function should then instantiate this class with the required data and use println() with string templating to produce the exact output string.

kotlin
data class User(val name: String, val id: Int, val nickname: String?)

fun main() {
    val user = User("Alex", 1, null)
    println("Welcome, ${user.name}! Your ID is ${user.id}.")
}
kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.