Kotlin – Keywords

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.

(a) Kotlin Hard Keywords

Following is a list of hard keywords and they cannot be used as identifiers:

asas?breakclass
continuedoelsefalse
forfunifin
!ininterfaceis!is
nullobjectpackagereturn
superthisthrowtrue
trytypealiastypeofval
varwhenwhile

(b) Kotlin Soft Keywords

Following is the list of keywords (soft) in the context when they are applicable and can be used as identifiers in other contexts:

bycatchconstructordelegate
dynamicfieldfilefinally
getimportinitparam
propertyreceiversetsetparam
valuewhere

(c) Kotlin Modifier Keywords

Following is the list of tokens which act as keywords in modifier lists of declarations and can be used as identifiers in other contexts:

actualabstractannotationcompanion
constcrossinlinedataenum
expectexternalfinalinfix
inlineinnerinternallateinit
noinlineopenoperatorout
overrideprivateprotectedpublic
reifiedsealedsuspendtailrec
vararg

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply