Kotlin is a modern, expressive programming language developed by JetBrains. It's designed to be fully interoperable with Java while offering enhanced features and a more concise syntax.
To begin your Kotlin journey, you'll need to install Kotlin on your system. Once installed, you can start writing Kotlin code using any text editor or IDE that supports Kotlin.
Kotlin's syntax is designed to be clean and intuitive. Here's a simple "Hello, World!" program in Kotlin:
fun main() {
println("Hello, World!")
}
Let's break down this example:
fun
declares a functionmain()
is the entry point of a Kotlin programprintln()
is used to print text to the consoleKotlin uses type inference to determine variable types. You can declare variables using val
for read-only variables and var
for mutable variables.
val name: String = "John" // Immutable
var age: Int = 30 // Mutable
var height = 1.75 // Type inferred as Double
For more details on variables and data types, check out the guides on Kotlin Variables and Kotlin Data Types.
Kotlin supports standard control flow structures like if-else statements, when expressions (similar to switch in other languages), and various types of loops.
val number = 10
if (number > 0) {
println("Positive number")
} else if (number < 0) {
println("Negative number")
} else {
println("Zero")
}
For more on conditional statements, see Kotlin If-Else Statements.
val day = 3
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
else -> "Weekend"
}
println(dayName) // Output: Wednesday
Learn more about the powerful Kotlin When Expression.
Functions in Kotlin are declared using the fun
keyword. They can have parameters and return values.
fun greet(name: String): String {
return "Hello, $name!"
}
val greeting = greet("Alice")
println(greeting) // Output: Hello, Alice!
Explore more about Kotlin Function Basics and Kotlin Function Parameters.
Kotlin's type system is designed to eliminate the danger of null references. By default, variables cannot hold null values unless explicitly declared as nullable.
var nonNullable: String = "Hello"
// nonNullable = null // This would cause a compilation error
var nullable: String? = "Hello"
nullable = null // This is allowed
For more on handling null values safely, check out Kotlin Nullable Types and Kotlin Safe Calls.
This introduction covers the basics of Kotlin. As you continue your journey, explore topics like Kotlin Classes, Kotlin Coroutine Basics, and Kotlin Java Interoperability to unlock the full potential of this powerful language.