This content originally appeared on DEV Community and was authored by Ge Ji
Welcome to your first Kotlin lesson! This course will take you from “why learn Kotlin” to “how to learn it”, helping you build a complete learning framework. You’ll understand Kotlin’s core value while gaining hands-on experience in setting up your environment and developing your first program, laying a solid foundation for further study.
I. Why Learn Kotlin? — First, Understand the “Purpose of Learning It”
Before writing any code, we first need to clarify: What exactly is Kotlin? Where is it used in the industry? What advantages does it have compared to familiar languages like Java and Python? This will help you establish learning goals and avoid following trends blindly.
1. Programming Language Positioning: A Modern Language Focused on “Conciseness, Safety, and Multi-platform Support”
Kotlin is a statically typed programming language introduced by JetBrains (the company behind popular tools like IntelliJ IDEA and PyCharm) in 2011. In 2017, it was officially designated by Google as the preferred language for Android development, and in 2019, it became a “first-class citizen” in the Java ecosystem (fully compatible with Java). Its core positioning is: significantly simplifying code writing while ensuring performance and security, with support for multi-platform development.
2. Industry Application Scenarios: Beyond Android, Its Uses Are More Extensive Than You Think
Many people think Kotlin is only for Android development, but its application scenarios have long expanded across multiple domains:
- Android Development: This is Kotlin’s core scenario. Currently, over 70% of new apps on Google Play are developed using Kotlin, including Google’s own Gmail and Maps;
- Backend Development: Supports mainstream frameworks like Spring Boot and Ktor, serving as a replacement for Java in developing high-performance server programs with significantly less code (e.g., a simple interface requires 30-50% less code in Kotlin than Java);
- Cross-platform Development: Through Kotlin Multiplatform Mobile (KMM), it enables simultaneous Android and iOS app development with over 70% shared business logic code, reducing redundant development;
- Other Scenarios: It can also be used for desktop applications (with Compose Desktop), data science (collaborating with Python), and other fields, with a rapidly expanding ecosystem.
3. Comparison with Java/Python: Kotlin’s “Differentiated Advantages”
(1) vs. Java: Solving “Historical Burdens” with Greater Conciseness and Safety
Java is a classic enterprise-level language but was born in 1995 with many “historical burdens” that Kotlin was specifically designed to address:
- More Concise Code: For example, defining a data class (for storing user information, order details, etc.) requires writing getter/setter methods, toString, equals, etc. in Java (at least 50 lines of code), while Kotlin needs just one line: data class User(val name: String, val age: Int);
- Null Safety: “NullPointerException” is the most common cause of crashes in Java, but Kotlin enforces a distinction between “nullable types” and “non-null types”, catching errors at compile time (e.g., String is always non-null, while String? allows null values), fundamentally reducing null pointer issues;
- Support for Modern Syntax: Built-in Lambda expressions, coroutines (simplifying asynchronous programming), extension functions (adding methods to existing classes without inheritance), etc., while Java only added Lambda support in Java 8 with more cumbersome syntax;
- 100% Java Compatibility: Can directly call Java libraries, use Java frameworks, and even mix Kotlin and Java code in the same project, resulting in extremely low migration costs (e.g., legacy Java projects can be gradually refactored with Kotlin).
(2) vs. Python: Balancing “Flexibility” with “Performance and Safety”
Python is a beginner-friendly dynamically typed language, but Kotlin has two key advantages in enterprise-level development:
- Static Typing + Compile-time Checks: Python uses dynamic typing (variable types are determined at runtime), which can cause runtime crashes due to “type errors” (e.g., passing a string to a function expecting a number). Kotlin, being statically typed, checks for type errors at compile time, making large projects easier to maintain;
- Superior Performance: Kotlin compiles to bytecode running on the JVM (Java Virtual Machine), executing 5-10 times faster than Python (especially in loops and computationally intensive scenarios), making it more suitable for developing high-performance applications;
- More Mature Enterprise Ecosystem: While Python excels in data science and script development, its enterprise-level ecosystem for backend and mobile development (e.g., distributed frameworks, security frameworks) is less mature than Kotlin’s Java-based ecosystem;
- Of course, Kotlin can complement Python’s strengths (like ease of entry and rich data science libraries) through “collaboration”: for example, using Kotlin to write backend services that call Python machine learning models.
II. Setting Up the Kotlin Learning Environment: 3 Steps from “Zero” to “Writing Code”
JiGe recommend learning Kotlin directly through Kotlin Playground. Kotlin Playground (https://play.kotlinlang.org/) is an official online platform from JetBrains for editing and running Kotlin code. It offers simple functionality and a smooth experience. Simply click “Run” to experiment with code snippets. Of course, you’ll need to first understand how to set up a Kotlin environment.
Learning Kotlin doesn’t require a complex environment. The core tools are JDK (Java Development Kit, required for Kotlin execution) and IntelliJ IDEA (development tool, officially recommended by JetBrains, with a free Community Edition). Below are detailed installation steps by operating system to ensure every student can get set up.
1. Step 1: Install and Configure JDK (Essential! Kotlin Depends on JVM)
Kotlin code ultimately compiles to JVM bytecode, so you must first install the JDK. We recommend installing JDK 11 (a long-term support version that’s stable and compatible with all mainstream frameworks).
(1) Installing JDK on Windows
- Download JDK: Visit the Oracle JDK Download Page (or use domestic mirrors like Huawei Cloud or Alibaba Cloud), select “Windows x64 Installer” (.exe file). Note that you’ll need to register a free Oracle account;
- Install JDK: Double-click the installer and click “Next” throughout, noting the installation path (e.g., C:\Program Files\Java\jdk-11);
- Configure environment variables: Right-click “This PC” → “Properties” → “Advanced system settings” → “Environment Variables”; In “System Variables”, click “New”, enter JAVA_HOME as the variable name and your JDK installation path as the variable value (e.g., C:\Program Files\Java\jdk-11); Find Path in “System Variables”, click “Edit” → “New”, enter %JAVA_HOME%\bin, then “New” again and enter %JAVA_HOME%\jre\bin (if JDK 11 lacks a jre folder, open Command Prompt and run bin\jlink.exe –module-path jmods –add-modules java.desktop –output jre to generate it);
- Verify installation: Open “Command Prompt” (Win+R, type cmd), enter java -version. If it displays “java version “11.xxx””, installation is successful.
(2) Installing JDK on macOS
- Download JDK: Visit the Oracle website and select “macOS x64 DMG Installer”;
- Install JDK: Double-click the DMG file and either drag it to the “Applications” folder or follow the prompts to complete installation;
- Configure environment variables (if needed): Open “Terminal” (Launchpad → Other → Terminal); Enter sudo nano /etc/profile (enter your password), then add at the end of the file:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
Press Ctrl+O to save, Ctrl+X to exit, then enter source /etc/profile to apply changes;
- Verify: In Terminal, enter java -version. If it displays JDK 11 version, installation is successful.
(3) Installing JDK on Linux
For Ubuntu:
- Download JDK: From the official website, select “Linux x64 Compressed Archive” (.tar.gz file);
- Extract to specified directory: Open Terminal and enter sudo tar -zxvf jdk-11xxx.tar.gz -C /usr/local/ (replace xxx with the specific version number);
- Configure environment variables: Enter sudo nano /etc/profile and add at the end:
export JAVA_HOME=/usr/local/jdk-11xxx
export PATH=$JAVA_HOME/bin:$PATH
After saving and exiting, enter source /etc/profile;
- Verify: In Terminal, enter java -version. If it displays the version, installation is successful.
2. Step 2: Download and Initialize IntelliJ IDEA (Free Community Edition)
IntelliJ IDEA (referred to as IDEA) is the most convenient tool for Kotlin development, supporting code completion, syntax checking, debugging, and more. The Community Edition is completely free and sufficient for learning purposes.
(1) Download IDEA
Visit the JetBrains website and select the “Community Edition” for your operating system (.exe for Windows, .dmg for macOS, .tar.gz for Linux).
(2) Install IDEA
- Windows: Double-click the installer, check “Create desktop shortcut” and “Associate .java/.kt files”, then click “Next” throughout;
- macOS: Double-click the .dmg file and drag IDEA to the “Applications” folder;
- Linux: Extract the .tar.gz file to the /opt/ directory, navigate to the bin folder, and double-click idea.sh to launch.
(3) Initialize IDEA (First Launch)
- On first launch, you’ll be prompted to “Import settings”. Select “Do not import settings” (recommended for beginners) and click “OK”;
- Choose a theme (Light/Dark, based on preference) and click “Next: Featured plugins”;
- Check if the “Kotlin” plugin is selected (included by default in IDEA Community Edition, no additional installation needed). If not, select it manually, click “Install”, then “Next”;
- Click “Start using IntelliJ IDEA” to complete initialization.
3. Step 3: Write Your First Kotlin Program “Hello World”
This step will guide you through the complete process of “creating a new project → writing code → running the program” — it’s very straightforward!
(1) Create a New Kotlin Project
- Open IDEA and click “New Project”;
- Select “Kotlin” from the left list and “Kotlin/JVM” on the right (JVM-based Kotlin project, ideal for beginners);
- Fill in project information: “Name”: Project name, e.g., “KotlinFirstDemo”; “Location”: Project save path, e.g., “D:\KotlinProjects”; “JDK”: Select the JDK 11 we installed earlier (if not displayed, click “Add JDK” and manually select the path);
- Click “Create” and wait for IDEA to initialize the project (may take a few seconds the first time as it downloads necessary dependencies).
(2) Create a Kotlin Source File
- After project initialization, the project directory will appear on the left. Locate the src/main/kotlin folder (the default directory for Kotlin source code);
- Right-click the kotlin folder and select “New” → “Kotlin Class/File”;
- In the popup window, enter “HelloWorld” for “Name” (note that Kotlin filenames should typically start with a capital letter, matching the class name), select “File” for “Kind” (suitable for simple code), and press “Enter”.
(3) Write the “Hello World” Code
In the newly created HelloWorld.kt file, enter the following code:
// First Kotlin program: Print Hello World
fun main() {
println("Hello, Kotlin!")
}
Code explanation:
- fun main(): Kotlin’s entry function (similar to Java’s main method), where program execution begins;
- println(“Hello, Kotlin!”): Print statement that outputs the string in parentheses to the console;
- // First Kotlin program…: Single-line comment, which we’ll discuss in detail later.
(4) Run the Program
There are two simple ways to run it:
- Click the run button: On the left side of the code editor, you’ll see a green “play button” (
). Click it and select “Run ‘HelloWorldKt'”;
- Right-click to run: Right-click the HelloWorld.kt file and select “Run ‘HelloWorldKt'”.
After successful execution, the “Run” panel at the bottom will display the output: Hello, Kotlin!. Congratulations! You’ve successfully run your first Kotlin program.
III. Analyzing the Kotlin Project Structure: Understanding “Every File in the Directory”
New IDEA users might find the project directory unfamiliar, but Kotlin project structures are well-organized. Understanding them will help you manage code more efficiently. Let’s break down the core directories and files using our newly created “KotlinFirstDemo” project.
1. Core Directory Structure (Focus on These 3 Folders)
KotlinFirstDemo/ # Project root directory
├─ .idea/ # IDEA project configuration folder (auto-generated, no manual changes needed)
├─ gradle/ # Gradle build tool configuration (auto-generated, manages dependencies)
├─ src/ # Core directory for source code and resource files
│ ├─ main/ # Main program directory (where you'll write business code)
│ │ ├─ kotlin/ # Kotlin source code directory (place .kt files here)
│ │ └─ resources/ # Resource file directory (e.g., images, configuration files)
│ └─ test/ # Test program directory (for test code, not needed for beginners)
│ └─ kotlin/ # Kotlin directory for test code
├─ build.gradle.kts # Gradle build script (configures project dependencies, Kotlin version, etc.)
└─ settings.gradle.kts # Gradle project settings (e.g., project name, module management)
Pay special attention to: src/main/kotlin (for writing code) and src/main/resources (for resources). Beginners don’t need to modify other directories and files — keep them as default.
2. Source File Format: .kt Suffix is Key
Kotlin source files have the unified suffix .kt (e.g., HelloWorld.kt, User.kt), which distinguishes them from Java files (.java) and Python files (.py).
A .kt file can contain multiple classes, functions, or variables (e.g., adding a User class to HelloWorld.kt), but it’s advisable to follow the “single responsibility principle”: one file should correspond to one core class or function (e.g., User.kt contains only the User class, Order.kt contains only the Order class) for easier maintenance.
3. Common IDEA Operations: “Tips” to Improve Development Efficiency
As a beginner, mastering these common operations will make coding smoother:
(1) Creating New Files/Classes
Besides the earlier method of “right-click → New → Kotlin Class/File”, you can use shortcuts:
- Windows/Linux: Alt + Insert (hold Alt and press Insert);
- macOS: Cmd + N (hold Command and press N). In the popup menu, you can choose “File” (ordinary file), “Class”, “Data Class”, etc., as needed.
(2) Running Code
In addition to clicking the “play button”, use shortcuts:
- Run current file: Shift + F10 (Windows/Linux) / Ctrl + R (macOS);
- Run specific program: If your project has multiple entry functions, click the “run configuration” in the top-right corner of IDEA (e.g., “HelloWorldKt”), select the program to run, then click the play button.
(3) Debugging Techniques (Core for Troubleshooting Code Errors)
When code results don’t match expectations, use “debugging” to step through execution:
- Add breakpoints: Click next to the line number (left side of the code line) to create a red dot (breakpoint), e.g., on the println line;
- Start debugging: Click the “debug button” (green bug icon
) or use the shortcut Shift + F9 (Windows/Linux) / Ctrl + D (macOS);
- Debug controls: After debugging starts, the “Debug” panel appears at the bottom. Common control buttons (left to right):
- “Step Over” (F8): Execute next step (without entering function internals);
- “Step Into” (F7): Enter current function (e.g., for custom functions, click to see execution);
- “Resume Program” (F9): Continue execution to next breakpoint;
- “Stop” (red square): Terminate debugging.
During debugging, hover your mouse over variables to see their values, helping you quickly identify errors (e.g., whether variable values match expectations).
(4) Code Completion (Essential for Beginners to Reduce Typos)
IDEA’s code completion is powerful. Instead of typing complete words, press Ctrl + Space (Windows/Linux) or Cmd + Space (macOS) for suggestions, then press Enter to complete. For example, typing pri suggests print, println, etc.
IV. First Look at Kotlin Syntax Style: These “Details” Determine Code Quality
Syntax style is a programming language’s “writing conventions”. Good style makes code more readable and maintainable. Kotlin has clear syntax specifications — mastering these details will help you write “professional-grade” code from the start.
1. Code Comments: Helping Others Understand Your Code
Comments explain code without affecting execution, yet are crucial for “people” (including your future self). Kotlin supports three comment types:
(1) Single-line Comments (//)
Most commonly used for explaining single lines of code or short text, formatted as // comment content:
// Define a function to calculate sum of two numbers
fun add(a: Int, b: Int): Int {
return a + b // Return calculation result
}
(2) Multi-line Comments (/* … */)
Used for comments spanning multiple lines, formatted as /* comment content */ and can span lines:
/*
This is a multi-line comment example
The function below checks if a number is even
Parameter: num - integer to check
Return value: true (even) / false (odd)
*/
fun isEven(num: Int): Boolean {
return num % 2 == 0
}
Note: Kotlin’s multi-line comments support nesting (unlike Java):
/*
Outer comment
/* This is a nested inner comment */
Continuing outer comment
*/
(3) Documentation Comments (/** … */)
Used for generating API documentation (similar to Java’s Javadoc), typically for commenting classes, functions, properties, etc., with support for tags (e.g., @param for parameters, @return for return values):
/**
* Calculate product of two integers
* @param x first multiplier
* @param y second multiplier
* @return product of the two numbers
*/
fun multiply(x: Int, y: Int): Int {
return x * y
}
In IDEA, hovering over places where this function is used will automatically display the documentation comment, which is very convenient.
2. Semicolons at Statement End: Optional, Omitting is Recommended
Unlike Java, which requires ; at the end of each statement, Kotlin makes semicolons optional. Omitting them is recommended for cleaner code:
// Recommended style (no semicolons)
println("Hello")
val age = 20
// Allowed but not recommended (with semicolons)
println("World");
val name = "Kotlin";
Semicolons are only needed when multiple statements are written on the same line:
// Multiple statements on one line require semicolons
println("Hello"); println("Kotlin")
3. Code Indentation: Use Spaces Instead of Tabs
Indentation shows code hierarchy (e.g., function bodies and loop bodies need indentation). Kotlin recommends 4 spaces for indentation (IDEA automatically converts Tabs to 4 spaces by default):
// Correct indentation example
fun printNumbers() {
// Function body indented by 4 spaces
for (i in 1..5) {
// Loop body indented by another 4 spaces (total 8)
println(i)
}
}
// Incorrect example (no indentation, poor readability)
fun printLetters() {
for (c in 'a'..'c') {
println(c)
}
}
IDEA automatically handles indentation (adding correct indentation after pressing Enter), so you can focus on writing code.
4. Naming Conventions: “Unspoken Rules” for Meaningful Names
While Kotlin doesn’t enforce naming requirements, the industry follows common conventions that make code more understandable:
- Variables/functions/properties: Use “camelCase” (lowercase first letter, uppercase first letter of subsequent words), e.g., userName, calculateTotal();
- Classes/interfaces: Use “PascalCase” (uppercase first letter, uppercase first letter of subsequent words), e.g., User, OrderService;
- Constants: Use all uppercase with underscores separating words, e.g., MAX_SIZE, DEFAULT_TIMEOUT;
- Package names: All lowercase without underscores, typically using reversed domain names (e.g., for company domain com.example, package name could be com.example.myapp).
Examples:
// Class name (PascalCase)
class Student {
// Property (camelCase)
val studentName: String = "Tom"
// Function (camelCase)
fun getAge(): Int {
return 18
}
}
// Constant (all uppercase)
const val MAX_SCORE = 100
This content originally appeared on DEV Community and was authored by Ge Ji