Certainly! Kotlin syntax is designed to be intuitive and concise. Let's break down some key elements of Kotlin syntax with examples:
Kotlin supports both mutable and immutable variables.
Example
// Immutable variable (cannot be changed)
val name: String = "Alice"
// Mutable variable (can be changed)
var age: Int = 30
val
: Used to declare immutable variables.var
: Used to declare mutable variables.Functions in Kotlin are defined using the fun
keyword.
Example
fun add(a: Int, b: Int): Int {
return a + b
}
fun
: Keyword to define a function.add(a: Int, b: Int): Int
: Function signature specifying parameter types and return type.Kotlin supports if-else statements, similar to many other languages.
Example
val num = 10
if (num > 0) {
println("Positive")
} else {
println("Non-positive")
}
if
: Used for conditional branching.else
: Optional block executed when the condition is false.Kotlin has built-in null safety features to prevent null pointer exceptions
Example
var name: String? = "John" // Nullable String
// Safe call operator
println("Length: ${name?.length}")
String?
: Nullable String type.?.
: Safe call operator, returns null if the receiver is null.Classes are defined using the class
keyword in Kotlin.
Example
class Person(val name: String, var age: Int) {
fun speak() {
println("$name is $age years old.")
}
}
class
: Keyword used to define a class.val name: String
: Property declaration for immutable property.var age: Int
: Property declaration for mutable property.fun speak()
: Member function declaration.Kotlin allows you to embed variables directly in strings.
Example
val name = "Alice"
val age = 30
println("Name: $name, Age: $age")
$name
and $age
: Variables interpolated directly into the string.Kotlin supports both for
and while
loops.
Example
// For loop
for (i in 1..5) {
println(i)
}
// While loop
var count = 0
while (count < 5) {
println("Count: $count")
count++
}
for (i in 1..5)
: Iterates from 1 to 5.while (count < 5)
: Executes a block of code repeatedly while a condition is true.Understanding these basic syntax elements will give you a solid foundation to start writing Kotlin code.