Kotlin First Program
Welcome to the exciting world of Kotlin programming! In this tutorial, we'll write and understand our very first Kotlin program. By the end of this lesson, you'll have a solid understanding of the basic structure of a Kotlin program and be able to run your own code.
Introduction
Every programming journey begins with that first program, and in the programming tradition, we'll start with a simple "Hello, World!" example. This small program might seem trivial, but it serves several important purposes:
- It confirms that your development environment is set up correctly
- It introduces you to the basic syntax of the language
- It helps you understand the core components needed to run a program
Let's dive in!
Your First Kotlin Program
Here's a simple Kotlin program that prints "Hello, World!" to the console:
fun main() {
println("Hello, World!")
}
When you run this program, you should see the following output:
Hello, World!
That's it! You've just written your first Kotlin program. Now let's break it down to understand what's happening.
Understanding the Structure
The main()
Function
In Kotlin, the main()
function serves as the entry point of your program. When you run a Kotlin application, the execution begins from this function:
fun main() {
// Code inside main function
}
The fun
keyword indicates that we're defining a function. The name main
is special - it tells the Kotlin runtime that this is where program execution should begin.
The println()
Function
Inside our main()
function, we use the println()
function to display text on the console:
println("Hello, World!")
This function prints the provided text followed by a line break. If you want to print without a line break, you can use print()
instead:
print("Hello, ")
print("World!")
Output:
Hello, World!
Alternative main()
Function Syntax
Kotlin also supports a more traditional main function signature that accepts command-line arguments:
fun main(args: Array<String>) {
println("Hello, World!")
// You can access command-line arguments
if (args.isNotEmpty()) {
println("Arguments passed:")
for (arg in args) {
println(arg)
}
}
}
The args
parameter is an array of strings containing any command-line arguments passed when the program is executed.
Exploring More Features
Let's enhance our first program to use some more Kotlin features:
fun main() {
// Declare a variable to store the name
val name = "Kotlin Beginner"
// Use string templates for dynamic output
println("Hello, $name!")
// Calculate and display the current year
val currentYear = 2023
val kotlinAge = currentYear - 2011
println("Kotlin is about $kotlinAge years old.")
// Using conditions
if (kotlinAge > 10) {
println("Kotlin is a mature language.")
} else {
println("Kotlin is still young.")
}
}
Output:
Hello, Kotlin Beginner!
Kotlin is about 12 years old.
Kotlin is a mature language.
Real-World Application
Let's create a slightly more practical example that might be used in a real application - a simple temperature converter:
fun main() {
// Prompt for user input
print("Enter temperature in Celsius: ")
// Read input and convert to Double
val celsius = readLine()?.toDoubleOrNull()
if (celsius != null) {
// Calculate Fahrenheit
val fahrenheit = (celsius * 9/5) + 32
// Display the result with formatted output
println("$celsius°C is equal to $fahrenheit°F")
// Add weather description
when {
celsius < 0 -> println("That's freezing!")
celsius < 10 -> println("That's very cold!")
celsius < 20 -> println("That's cool weather.")
celsius < 30 -> println("That's warm weather.")
else -> println("That's hot!")
}
} else {
println("Invalid input. Please enter a valid number.")
}
}
Example interaction:
Enter temperature in Celsius: 25
25.0°C is equal to 77.0°F
That's warm weather.
Running Your Kotlin Program
There are several ways to run your Kotlin program:
-
Using an IDE like IntelliJ IDEA:
- Create a new Kotlin file
- Write your code
- Click the green "Run" button next to the
main()
function
-
Using the command line:
- Save your code in a file with
.kt
extension, e.g.,HelloWorld.kt
- Compile it:
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
- Run it:
java -jar HelloWorld.jar
- Save your code in a file with
-
Online playgrounds:
- Visit Kotlin Playground
- Write your code and click "Run"
Common Mistakes to Avoid
When writing your first Kotlin program, watch out for these common issues:
-
Forgetting the main function: Your program must have a
main()
function as the entry point. -
Case sensitivity: Kotlin is case-sensitive, so
main()
andMain()
are considered different functions. -
Missing quotes: String literals must be enclosed in quotes, like
"Hello, World!"
. -
Semicolons: Unlike some languages, Kotlin doesn't require semicolons at the end of statements (though they're optional).
Summary
Congratulations! You've successfully written and understood your first Kotlin program. We've covered:
- The basic structure of a Kotlin program
- The role of the
main()
function as the entry point - Using
println()
for output - Working with variables and string templates
- Building a simple practical application
- Different ways to run your Kotlin code
Kotlin's clean syntax and powerful features make it an excellent language for beginners and experienced developers alike. As you continue your journey, you'll discover how Kotlin's modern design helps you write more concise, readable, and safer code.
Exercises
To reinforce your learning, try these exercises:
-
Modify the "Hello, World!" program to greet you by your name.
-
Create a program that asks for the user's birth year and calculates their age.
-
Write a program that prints a simple pattern using multiple
println()
statements, like:*
**
***
****
***** -
Enhance the temperature converter to also convert from Fahrenheit to Celsius based on user choice.
Additional Resources
- Kotlin Official Documentation
- Kotlin Playground - Practice Kotlin online
- Kotlin Koans - Interactive programming exercises
- Kotlin By Example - Learn Kotlin with small, annotated examples
Happy coding with Kotlin!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)