
Basic Syntax in Kotlin
📌 Basic Syntax in Kotlin
Kotlin has a clean and concise syntax, making it easier to read and write. Let's go through some of the basic concepts.
✅ 1. Hello World Program
fun () { println("Hello, World!")}
fun
→ Declares a function.main()
→ Entry point of the Kotlin program.println()
→ Prints output with a newline.
✅ 2. Variables and Data Types
Variables in Kotlin
val
→ Immutable (read-only) variable. Likefinal
in Java.var
→ Mutable variable.
val name: String = "John" // Immutablevar age: Int = 25 // Mutableprintln("Name: $name, Age: val city = "New York" // Inferred as Stringvar price = 199.99 // Inferred as Double
✅ 3. Data Types
Common data types in Kotlin:
Int
→ Integer (e.g., 10, -20)Double
→ Floating-point number (e.g., 10.5, 99.99)Char
→ Single character (e.g., 'A', 'B')String
→ Text (e.g., "Hello")Boolean
→ True or FalseArray
→ Collection of itemsList
→ Ordered collection
✅ 4. Conditional Statements
If-Else
val num = 10if (num > 0) { println("Positive number")} else { println("Negative number")}
If-Else as Expression
val a = 15val b = 10val max = if (a > b) a else bprintln("Max: $max")
✅ 5. When Statement (Switch Equivalent)
val dayName = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" else -> "Invalid Day"}println(dayName)
✅ 6. Loops
For Loop
for (i in 1..5) { println(i) // Output: 1 to 5}for (i in 1 until 5) { println(i) // Output: 1 to 4}val numbers = arrayOf(10, 20, 30)for (num in numbers) { println(num)}
While Loop
var i = 1while (i <= 5) { println(i) i++}
✅ 7. Functions
fun (a: Int, b: fun (a: Int, b: var name: String? = nullprintln(name?.length) // Safe call operator
?.
→ Safe call operator to avoid NullPointerException.!!
→ Non-null assertion operator (throws exception if null).
✅ 9. Classes and Objects
class Person(val name: String, var age: Int) { fun () { println("Hello, my name is $name and I am $age years old.") }}val person = Person("Alice", 30)person.greet()
✅ 10. Conclusion
Kotlin has a clear and expressive syntax.
Variables can be mutable (
var
) or immutable (val
).Control flow is managed using
if-else
,when
,for
, andwhile
.Functions are simple and support concise expressions.
Null safety is a core feature.