KOTLIN Tutorial



SYNTAX IN KOTLIN


Kotlin Syntax

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.

Declaring Variables

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 in Kotlin

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")

Control Flow

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")
}

Null Safety

Kotlin provides built-in null safety mechanisms to handle null values gracefully:

  • Nullable Types: Use ? to declare nullable types.
  • Safe Call Operator: Use ?. to safely call methods or access properties of nullable objects.
var name: String? = null
println(name?.length)  // Safely prints null without causing an exception

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review