Writing Your First Kotlin Program: A Step-by-Step Guide
Kotlin, developed by JetBrains, has become a popular programming language due to its conciseness, expressiveness, and interoperability with Java. It is widely used for Android app dev
elopment, but its application extends far beyond that, from backend development to even web and desktop applications. Whether you’re coming from a Java background or are completely new to programming, writing your first Kotlin program is straightforward. This guide will walk you through setting up your environment and writing your first Kotlin application.Writing Your First Kotlin Program
Now that you have everything set up, it’s time to write your first Kotlin program—a simple “Hello, World!” application.
Create a Kotlin File
In your newly created project, you’ll see a src
folder where all your Kotlin code will reside.
- Right-click on the
src
folder, then choose New > Kotlin File/Class. - Name the file
Main.kt
.
Writing the “Hello, World!” Program
Open the newly created Main.kt
file and write the following Kotlin code:
fun main() {
println("Hello, World!")
}
Explanation of the Code:
- fun: This keyword is used to declare a function in Kotlin. In this case, we are defining the
main
function, which is the entry point of the application. - main(): The
main
function is special in Kotlin. It is where the program starts execution, similar to Java’spublic static void main
. - println(): This function prints text to the console. In this case, it prints
"Hello, World!"
.
Running Your Program
- To run the program, right-click on the file in the project window and choose Run Main.kt.
- You should see
Hello, World!
printed in the console at the bottom of the IDE.
Congratulations! You’ve just written and executed your first Kotlin program.
Understanding Kotlin Basics
Let’s explore some basic Kotlin concepts that will help you in writing more complex programs.
Variables
Kotlin supports two types of variables:
- val: Immutable variable (like
final
in Java). Once assigned, its value cannot be changed.
val name = "Kotlin" // Immutable variable
- var: Mutable variable. You can change its value.
var age = 25 // Mutable variable
Functions
Functions in Kotlin are declared using the fun
keyword. Here’s an example of a function that adds two numbers:
fun addNumbers(a: Int, b: Int): Int {
return a + b
}
- fun: Declares a function.
- a: Int, b: Int: These are the function parameters, both of type
Int
. - : Int: Specifies the return type of the function.
- return: Returns the sum of
a
andb
.
Null Safety
Kotlin’s type system is designed to eliminate the danger of null references. By default, variables cannot hold null values. If you need a variable to hold a null value, you must explicitly mark it as nullable using ?
.
var name: String? = null // Nullable variable
Kotlin forces you to handle potential null values safely using techniques like:
- Safe Call (
?.
): If the variable is null, the call returnsnull
instead of throwing aNullPointerException
.
name?.length // Returns the length if name is not null, else returns null
Elvis Operator (?:
): Provides a default value when the variable is null.
val length = name?.length ?: 0 // Returns 0 if name is null
Adding More to the Program
Let’s modify the initial “Hello, World!” program to accept user input and perform some basic operations.
fun main() {
println("Enter your name:")
val name = readLine()
println("Hello, $name!")
}
Explanation:
- readLine(): This function reads input from the user. The input is stored in the
name
variable. - String Interpolation: Kotlin allows you to embed variables directly into strings using the
$
symbol. In this case,$name
inserts the value of thename
variable into the string.
When you run this modified program, it will ask for your name and greet you personally.
Using Conditional Statements
In Kotlin, you can use traditional conditional statements like if
, else
, and when
.
Example of if-else
:
fun main() {
println("Enter your age:")
val age = readLine()?.toIntOrNull() ?: 0
if (age >= 18) {
println("You are an adult.")
} else {
println("You are not an adult.")
}
}
- The
toIntOrNull()
function converts the user input to an integer. If the input is invalid (e.g., not a number), it returnsnull
. - The Elvis operator (
?:
) ensures that if the input is invalid, the default value of0
is used.
Example of when
:
fun main() {
val dayOfWeek = 3
when(dayOfWeek) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
else -> println("Invalid day")
}
}
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.