Kotlin Keywords and Identifiers

Kotlin Keywords

Keywords are predefined, reserved words used in Kotlin programming that have special meanings to the compiler. These words cannot be used as an identifier. For example:

val score = 5

Here, val is a keyword. It indicates that score is a variable.

Since keywords are part of the Kotlin syntax, you cannot use them as a variable name (identifier). For example:

val for = 5 // Error code

Both val and for are keywords. Hence, you cannot declare a variable named for in Kotlin.


Here's a list of all keywords in Kotlin:

Kotlin keywords List
as break class continue do else
false for fun if in interface
is null object package return super
this throw true try typealias typeof
val var when while    

These keywords are called hard keywords.


Soft Keywords

Except these 28 hard keywords, there are many soft keywords in Kotlin. Soft keywords are treated as keywords only in certain context. For example,

public acts as a keyword when you are making members of a class public.

class TestClass {
    public val name = "Kotlin"
}

Here, public acts as a keyword.

You can also create a variable named public.

val public = true

Here, public is a Boolean variable.

Some soft variables in Koltin are: override, private, field etc.


Kotlin Identifiers

Identifiers are the name given to variables, classes, methods etc. For example:

var salary = 7789.3

Here, var is a keyword, and salary is the name given to the variable (identifier).


Here are the rules and conventions for naming a variable (identifier) in Kotlin:

  • An identifier starts with a letter or underscore followed by zero, letter and digits.
  • Whitespaces are not allowed.
  • An identifier cannot contain symbols such as @, # etc.
  • Identifiers are case sensitive.
  • When creating variables, choose a name that makes sense. For example, score, number, level makes more sense than variable name such as s, n, and l although they valid.
  • If you choose a variable name having more than one word, use all lowercase letters for the first word and capitalize the first letter of each subsequent word. For example, speedLimit.

Some valid identifiers:

  • score
  • level
  • highestScore
  • number1
  • calculateTraffic

Some invalid identifiers:

  • class
  • 1number
  • highest Score
  • @pple
Did you find this article helpful?