Welcome to our comprehensive guide on Kotlin Keywords! This tutorial is designed for both beginners and intermediate learners, focusing on practical knowledge with real-world examples. Let's dive into the world of Kotlin programming language.
Kotlin keywords are special words used to define program structures, control flow, and data types. They are essential for writing a correct and efficient Kotlin program.
Val and Var are used to declare variables. The main difference is that Val is used for immutable variables (once assigned, cannot be changed), while Var is for mutable variables (can be changed).
// Declaring a constant (immutable) variable using Val
val myConstant: Int = 10
// Declaring a mutable variable using Var
var myMutable: Int = 10
myMutable = 20 // This is valid as myMutable is mutableFun is not a keyword, but it is used to define functions in Kotlin.
fun greet(name: String): String {
return "Hello, $name!"
}
// Calling the function
val greeting = greet("World")
print(greeting) // Output: Hello, World!The When keyword is used for conditional statements in Kotlin.
fun findEvenOdd(number: Int) {
when (number % 2) {
0 -> print("Even")
1 -> print("Odd")
}
}
// Calling the function
findEvenOdd(10) // Output: Even
findEvenOdd(11) // Output: OddInf represents infinity (positive or negative), and NaN represents Not-a-Number (a special floating-point value representing an undefined or unrepresentable mathematical value).
val positiveInfinity = Double.POSITIVE_INFINITY
val negativeInfinity = Double.NEGATIVE_INFINITY
val notANumber = Double.NaNThe In keyword is used in range checks.
fun isInRange(number: Int, start: Int, end: Int) = number in start..end
// Calling the function
println(isInRange(10, 5, 20)) // Output: true
println(isInRange(30, 5, 20)) // Output: falseWhat is the purpose of the `Val` keyword in Kotlin?
We hope this guide helps you understand Kotlin keywords better. Keep coding and happy learning! 🚀🚀