Kotlin Essentials: Understanding Basic Syntax with Clear Examples
Kotlin Basic Syntax
Kotlin offers a clean and expressive syntax, making it a great language for both beginners and experienced developers. Let’s break down some of the fundamental syntax elements of Kotlin, focusing on variables, conditions, loops, and functions.
Before getting started, if you'd like to try out this syntax and practice, visit an online Kotlin compiler.
Variable Declarations
1. Declaring Mutable Variables
In Kotlin, mutable variables can be declared using the var keyword. This means their values can be reassigned later in the code.
var mercury: String = "Mercury" // Declares a mutable String variable
mercury = "Venus" // Reassigns the value to "Venus"
2. Declaring Read-Only (Immutable) Variables
If you don’t want a variable to be reassigned, use val. This creates an immutable variable, which means it cannot be changed once assigned.
val mercury: String = "Mercury" // Declares an immutable variable
mercury = "Venus" // Compile-time error: "val cannot be reassigned"
Type Inference
Kotlin can infer the type of a variable without explicitly stating it. This makes your code more concise.
val noTypeUnMutable = "Hello" // Inferred as String
var noTypeIntMutable = 8765 // Inferred as Int
Basic Data Types
Kotlin supports standard data types like String, Int, and Double. One key point about strings in Kotlin is that they are immutable. If you reassign a mutable string, a new object is created under the hood.
Kotlin also includes unsigned integer types like UShort, UInt, and ULong.
var mutableString: String = "Hello"
mutableString = "World" // A new String object is created
Conditional Code
if Expressions
Kotlin’s if is an expression, meaning it can return a value. You can use it just like an if-else statement, or to assign values based on conditions.
val mercury = "Mercury"
if (mercury == "Mercury") {
println("Universe is intact.")
} else {
println("Universe out of order.")
}
Ternary Operator with if
In Kotlin, there’s no ternary conditional operator (? :) because if itself is an expression.
val amount = 2000
val isApproved = true
val status = if (amount > 1000 && isApproved) "Approved" else "In Progress"
println(status) // Prints "Approved"
when Expression
The when expression is Kotlin’s version of the switch statement. It’s powerful and can check multiple conditions, including ranges and types.
when (mercury) {
"Mercury" -> println("Universe is intact.")
"Venus" -> println("Universe is stable.")
else -> println("Universe out of order.")
}
You can also match values in ranges, or check types using when:
val temperature = 700
when (temperature) {
700 -> print("700")
0, 1, 2 -> print("0 OR 1 OR 2")
in 300..699 -> println("Temperature is moderate.")
!in 0..300 -> println("Temperature is too low.")earthSurfaceTemp() -> print("Whatever function will return.")is Int -> print("Data Type is Integer.")
else -> println("Temperature is extreme.")
}fun earthSurfaceTemp(): Int {
return 30;
}
Conditional logic using 'when'
when {
age < 18 && hasAccess -> println("False positive") // Executes if age is less than 18 and hasAccess is true
age > 21 && !hasAccess -> println("False negative") // Executes if age is greater than 21 and hasAccess is false
else -> println("All working as expected") // Executes if neither of the previous conditions are met
}
Using when as an Expression
val maxSurfaceTempInK:Int = 700;val surfaceTemp = when (maxSurfaceTempInK) {700 -> "700 normal"
else -> {"Not Suitable"}
}
Loops and Ranges
While Loop
The while loop repeats a block of code while a condition is true.
while (error > 0.0001) {
// Code block
}
Do-While Loop
A do-while loop ensures the code block executes at least once before checking the condition.
do {val command = readLine()} while (command != ":quit")
For Loops
Kotlin offers flexible for loops to iterate over ranges, collections, or even strings.
for (i in 1..10) println(i) // Iterates from 1 to 10 (inclusive)
for (i in 1 until 10) println(i) // Iterates from 1 to 9 (exclusive)
for (i in 100 downTo 1) println(i) // Iterates from 100 down to 1for (planet in planets) println(planet) // Iterates over a collection// iterate over strings character by characterfor (character in "Mercury") { println("$character, ") }
You can also use step to increment by a specific value:
for (i in 1..10 step 2) println(i) // 1, 3, 5, 7, 9
// 1..10 step 2 is equivalent to (1..10).step(2)for (i in 100 downTo 1 step 5) println(i) // 100, 95, 90, ..., 15, 10, 5// 100.downTo(1).step(5) - called as Infix functions// Infix functions thus allow writing more readable code with less clutter from parentheses.
Functions
Basic Function Declaration
Functions in Kotlin are declared using the fun keyword.
fun fib(n: Int): Long {
return if (n < 2) 1 else fib(n-1) + fib(n-2)
}
You can also use shorthand notation for functions with a single expression:
fun fib(n: Int): Long = if (n < 2) 1 else fib(n-1) + fib(n-2)
Main Function
The main function is the entry point of every Kotlin program. It takes an array of strings as input and has a default return type of Unit.
fun main(args: Array<String>) {
println("Hello, World!")
}
Default Parameter Values
fun exploreDirectory(path: String, depth: Int = 0) {
// Function body
}
This can be called with or without the optional parameter.
Extension Functions
StringUtils or DateUtils extend the functionality of existing classes by adding helper methods. In Kotlin, you can achieve this with extension functions, which allow you to add methods to classes you don’t own.fun main() {
fun Number.print() = println("Number $this")
fun Int.print() = println("Int $this")
val n: Number = 42
n.print()
}
fun main() {
fun Number.print() = println("Number $this")
fun Int.print() = println("Int $this")
val n: Number = 42
n.print()
}
Though n is an Int at runtime, Number.print is called at compile time. Note that extension functions are not polymorphic, so use them carefully when behavior based on type is expected.
Importing Extension FunctionsFor example, to use an extension function plusDays from a package "time", import it:import com.example.time.plusDays
Extension functions help you work around limitations of third-party APIs, adding methods or encapsulating repetitive code, which is especially useful in Android development.
EXCEPTION HANDLING
Kotlin only supports unchecked exceptions. You can throw and catch exceptions as shown below:fun reducePressureBy(bar: Int) {
throw IllegalArgumentException("Invalid pressure reduction by $bar")
}
try {
reducePressureBy(30)
} catch (e: IllegalArgumentException) {
// Handle exception
} catch (e: IllegalStateException) {
// Handle multiple exceptions
} finally {
// Code that always executes
}
Kotlin does not use the new keyword for object instantiation. For example, you can safely parse input with try and catch:val input: Int? = try {
inputString.toInt()
} catch (e: NumberFormatException) {
null // Returns null if input can't be parsed
}
Kotlin also provides the Nothing type for functions that never return:fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
val bitmap = card.bitmap ?: fail("Bitmap required")
bitmap.prepareToDraw()
Conclusion
n is an Int at runtime, Number.print is called at compile time. Note that extension functions are not polymorphic, so use them carefully when behavior based on type is expected.import com.example.time.plusDays
fun reducePressureBy(bar: Int) {
throw IllegalArgumentException("Invalid pressure reduction by $bar")
}
try {
reducePressureBy(30)
} catch (e: IllegalArgumentException) {
// Handle exception
} catch (e: IllegalStateException) {
// Handle multiple exceptions
} finally {
// Code that always executes
}
val input: Int? = try {
inputString.toInt()
} catch (e: NumberFormatException) {
null // Returns null if input can't be parsed
}
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
val bitmap = card.bitmap ?: fail("Bitmap required")
bitmap.prepareToDraw()
Kotlin’s concise and expressive syntax makes it a powerful language. From mutable and immutable variables to flexible conditional expressions and looping structures, Kotlin’s syntax is designed to be both readable and efficient. Whether you’re coming from Java or another language, Kotlin offers tools to write clean and safe code with minimal effort.
Comments
Post a Comment