Kotlin – Keywords

Kotlin keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier (variables names, package names, function names etc.) and if used then compiler will raise an exception.

Kotlin uses fun keyword to define a function, so if we we will try to use it as a variable name then it will be an exception. For example:

fun main() {
   var fun = "Zara Ali"  // Not allowed, throws an exception
   var age = 19          // Valid variable name

   println("Name = $fun")
   println("Age = $age")
}

When you run the above Kotlin program, it will generate the following output:

main.kt:2:7: error: expecting property name or receiver type
   var fun = "Zara Ali"  // Not allowed, throws an exception
      ^
main.kt:2:11: error: expecting '('
   var fun = "Zara Ali"  // Not allowed, throws an exception
          ^
main.kt:5:21: error: keyword cannot be used as a reference
   println("Name = $fun")
                    ^

Kotlin keywords have been categorised into three broad categories: (a) Hard Keywords (b) Soft Keywords (c) Modifier Keywords

As a good programming practice, it is highly recommended not to use any of the mentioned keywords to name any identifiers while coding in Kotlin.

Types of Keywords in Kotlin

We have two types of keywords:
1. Hard Keywords
2. Soft Keywords

1. Hard Keywords

These keywords cannot be used as identifiers. For example
This is valid:

//valid variable name
val myvar = 5

This is invalid:

//error: "else" cannot be used as a variable name
val else = 5
asclassbreakcontinuedoelse
forfunfalseifininterface
superreturnobjectpackagenullis
trythrowtruethistypeoftypealias
whenwhilevalvar

2. Soft Keywords

Soft keywords are the keywords that are used only in a certain context which means we can use them as identifier. Apart from the above list of keywords, there are other keywords that can be used as identifiers. For example, “by” is a soft keyword which delegates the implementation of an interface to another object. We can use the keyword “by” as identifier as well.

//valid code
fun main(args: Array) {
    val by=10
    println(by+10)
}

There are several other soft keywords available in Kotlin such as catch, get, finally, field etc.

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.