Kotlin, a statically typed programming language developed by JetBrains, is known for its concise syntax and interoperability with Java. This article aims to guide you through the basics of Kotlin’s syntax.
Getting Started with Kotlin Syntax
Let’s start with the quintessential “Hello, World!” program.
fun main(args: Array<String>) {
println("Hello, World!")
}
The fun
keyword denotes a function. main
is the starting point of the program. The JVM executes this function first.
Variables and Types in Kotlin
In Kotlin, we can define variables using var
and val
keywords.
var variable: String = "I can be changed"
val constant: String = "I cannot be changed"
var
declares a mutable variable, while val
declares an immutable (read-only) variable.
Control Flow in Kotlin
Kotlin provides several control flow constructs, such as if
, when
, for
, while
, and more.
val numbers = listOf(1, 2, 3, 4, 5)
for (number in numbers) {
println(number)
}
This loop iterates over each number
in numbers
and prints it.
Functions in Kotlin
Functions in Kotlin are declared using the fun
keyword.
fun greet(name: String): String {
return "Hello, $name!"
}
In this function, name
is a parameter and String
is the return type.