In Kotlin, you define variables and functions with specific syntax. Understanding Kotlinโs basic syntax is key to writing efficient and concise code.
Note:
The syntax for Kotlin is designed to be expressive and easy to read. Proper usage of keywords and structure is essential for writing clean code.
In Kotlin, you can declare variables using the val
(immutable) or var
(mutable) keywords:
val name: String = "Kotlin" // Immutable var age: Int = 5 // Mutable
Functions are defined using the fun
keyword. Hereโs how you declare and call a function:
fun greet(name: String) { println("Hello, $name!") } greet("Kotlin")
Kotlin supports typical control flow structures like if
, else
, when
, for
, while
, etc.
val number = 10 if (number > 5) { println("Number is greater than 5") } else { println("Number is 5 or less") }
Kotlin provides built-in null safety mechanisms to handle null values gracefully:
?
to declare nullable types.?.
to safely call methods or access properties of nullable objects.var name: String? = null println(name?.length) // Safely prints null without causing an exception
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!