Kotlin Syntax

Kotlin syntax is clean, simple, and readable, making it easy for beginners to learn and use. Below are the basic syntax rules with clear examples.


1. Kotlin Program Structure

Every Kotlin program starts from the main() function.



 

  • fun → keyword to define a function

  • main() → entry point of the program

  • { } → code block


2. Statements & Semicolons

  • Semicolons (;) are optional in Kotlin.



 


3. Variables in Kotlin

val (Read-only / Constant)



 

var (Mutable / Changeable)



 


4. Data Types

Kotlin automatically detects data types (type inference).



 


5. Comments

Single-line Comment

// This is a comment

Multi-line Comment

/*
This is
a multi-line comment
*/


6. Print Output

print("Hello ")
println("Kotlin")

7. String Templates

Use $ to insert variables in strings.

val name = "Kotlin"
println("Welcome to $name")

8. If-Else Condition

Kotlin allows if as an expression.

val a = 10
val b = 20
val max = if (a > b) a else b
println(max)

9. When Statement (Switch Alternative)

val day = 3

when (day) {
1 -> println(“Monday”)
2 -> println(“Tuesday”)
3 -> println(“Wednesday”)
else -> println(“Invalid Day”)
}


10. Loops

For Loop

for (i in 1..5) {
println(i)
}

While Loop

var i = 1
while (i <= 3) {
println(i)
i++
}

11. Functions

fun add(a: Int, b: Int): Int {
return a + b
}

Short form:

fun add(a: Int, b: Int) = a + b

12. Null Safety (Very Important)

var name: String? = null
println(name?.length)
  • ? allows null

  • ?. safe call operator


13. Class Syntax

class Person(val name: String, var age: Int)

fun main() {
val p = Person(“Rahul”, 25)
println(p.name)
}


Summary

  • Kotlin syntax is simple and expressive

  • Less boilerplate than Java

  • Built-in null safety

  • Beginner-friendly

You may also like...