Kotlin Keywords
Reserved words and their meanings in Kotlin
🔑 What are Kotlin Keywords?
Keywords are reserved words in Kotlin that have special meanings and cannot be used as identifiers. They control program flow, define structures, and provide language functionality.
// Keywords in action
fun main() {
val name = "Kotlin" // val, fun are keywords
if (name.isNotEmpty()) { // if is a keyword
println("Hello, $name!")
}
}
Keyword Categories
Declaration
Define variables and functions
val, var, fun, class
interface, object
Control Flow
Control program execution
if, else, when, for
while, do, break, continue
Modifiers
Control visibility and behavior
private, public, internal
protected, open, final
Special
Unique Kotlin features
suspend, inline, reified
companion, sealed
🔹 Declaration Keywords
Keywords used to declare variables, functions, and classes:
// Variable declarations
val immutableValue = "Cannot change"
var mutableVariable = "Can change"
// Function declaration
fun greet(name: String): String {
return "Hello, $name!"
}
// Class declaration
class Person(val name: String, var age: Int)
// Interface declaration
interface Drawable {
fun draw()
}
// Object declaration (singleton)
object Logger {
fun log(message: String) {
println("LOG: $message")
}
}
Usage:
val: Immutable variable (read-only)
var: Mutable variable
fun: Function declaration
class: Class definition
object: Singleton object
🔹 Control Flow Keywords
Keywords that control program execution flow:
fun demonstrateControlFlow(score: Int) {
// if-else
if (score >= 90) {
println("Excellent!")
} else if (score >= 70) {
println("Good!")
} else {
println("Keep trying!")
}
// when (similar to switch)
when (score) {
100 -> println("Perfect!")
in 90..99 -> println("Almost perfect!")
in 70..89 -> println("Good job!")
else -> println("Room for improvement")
}
// for loop
for (i in 1..5) {
if (i == 3) continue // Skip 3
if (i == 5) break // Stop at 5
println("Number: $i")
}
// while loop
var count = 0
while (count < 3) {
println("Count: $count")
count++
}
}
Output (for score = 85):
Good! Good job! Number: 1 Number: 2 Number: 4 Count: 0 Count: 1 Count: 2
🔹 Visibility Modifiers
Keywords that control access to classes, functions, and properties:
class BankAccount(private val accountNumber: String) {
private var balance: Double = 0.0 // Only accessible within this class
protected val createdAt = System.currentTimeMillis() // Accessible in subclasses
internal fun getAccountInfo(): String { // Accessible within the same module
return "Account: $accountNumber"
}
public fun deposit(amount: Double) { // Accessible everywhere (default)
if (amount > 0) {
balance += amount
}
}
fun getBalance(): Double = balance // public by default
}
// Inheritance modifiers
open class Animal(val name: String) { // open allows inheritance
open fun makeSound() { // open allows overriding
println("Some sound")
}
}
final class Dog(name: String) : Animal(name) { // final prevents inheritance
override fun makeSound() {
println("Woof!")
}
}
Visibility Levels:
- private: Visible only within the same class/file
- protected: Visible in subclasses
- internal: Visible within the same module
- public: Visible everywhere (default)
🔹 Special Kotlin Keywords
Unique keywords specific to Kotlin features:
// Suspend functions for coroutines
suspend fun fetchData(): String {
delay(1000) // Simulated network call
return "Data fetched"
}
// Inline functions
inline fun measureTime(block: () -> Unit) {
val start = System.currentTimeMillis()
block()
val end = System.currentTimeMillis()
println("Time taken: ${end - start}ms")
}
// Sealed classes
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
object Loading : Result()
}
// Companion object
class MathUtils {
companion object {
const val PI = 3.14159
fun square(x: Int) = x * x
}
}
// Data class
data class User(val name: String, val email: String)
// Usage examples
fun main() {
// Using companion object
println(MathUtils.PI)
println(MathUtils.square(5))
// Using data class
val user = User("John", "[email protected]")
println(user) // Automatic toString()
// Using sealed class
val result: Result = Result.Success("Hello")
when (result) {
is Result.Success -> println(result.data)
is Result.Error -> println(result.message)
Result.Loading -> println("Loading...")
}
}
Output:
3.14159 25 User(name=John, [email protected]) Hello