Kotlin, like many other programming languages, has a set of reserved words. These are keywords that have special meaning and purpose in the language syntax. When writing code, you cannot use these reserved words as variable names, function names, or any other identifiers. This article will guide you through these keywords and provide some examples to illustrate their usage.
What are Reserved Words?
Reserved words, also known as keywords, are pre-defined identifiers that are part of the language syntax. They tell the compiler about the structure and operations allowed in the program. They are integral to writing functions, loops, and various other constructs.
Common Reserved Words in Kotlin
Kotlin keywords can largely be divided into three categories:
- Statements
- Types
- Control Flow
Statements
packageimportclassfuninterface
Types
Int,String,Boolean, etc.
Control Flow
ifelsewhilereturn
Examples of Using Reserved Words
Let’s look at a simple code example with some common reserved words:
fun main() {
val name: String = "Kotlin"
if (name.isNotEmpty()) {
println("Hello, $name!")
} else {
println("Hello, world!")
}
}
In the code above:
fun- Defines a function in Kotlin.valandString- Define immutable variables and types.ifandelse- Used for control flow.
Why Can’t You Use Reserved Words?
Reserved words have predefined purposes in the language and determine the structure and control flow of programs. Using these words as variable names could lead to ambiguity and compilation errors.
For instance:
// Will cause a compilation error
val class: String = "User"
The code above will fail because class is a keyword that is reserved for declaring a class, not assigning a value.
Identifying Reserved Words
If you need to use a name that coincides with a reserved word, prefixes like backticks (`name`) can be utilized in Kotlin:
fun main() {
val `class` = "Not a Kotlin class"
println(`class`)
}
In this example, you 'trick' the compiler into accepting the reserved word as an identifier.