English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about keywords. The reserved keywords in Kotlin programming. In addition, you will also learn about identifiers and how to name variables.
Keywords are predefined reserved words used in Kotlin programming that have special meaning to the compiler. These words cannot be used as identifiers. 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 variable names (identifiers). For example:
val for = 5 //Error Codes
Both val and for are keywords, so you cannot declare a variable named for in Kotlin.
The following is a list of all keywords in Kotlin:
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.
Besides this28A hard keyword, Kotlin also has many soft keywords. Soft keywords are only considered keywords in specific contexts. For example,
When you set a class member to public, public acts as a keyword.
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 Kotlin include override, private, field, and so on.
Identifiers are the names provided for variables, classes, methods, and so on. For example:
var salary = 7789.3
Here, var is a keyword, and salary is the name given to the variable (identifier).
The following are the rules and conventions for naming variables (identifiers) in Kotlin:
Identifiers must start with a letter or underscore, followed by zero, letters, and numbers.
Spaces are not allowed.
Identifiers cannot contain symbols such as @, #, and so on.
Identifiers are case-sensitive.
When creating variables, choose a meaningful name. For example, score, number, level are more meaningful than variable names such as s, n, and l, although s, n, and l are also valid.
If you choose a variable name with multiple words, use all lowercase letters for the first word and capitalize each subsequent word. For example, speedLimit.
Some valid identifiers:
score
level
highestScore
number1
calculateTraffic
Some invalid identifiers:
class
1number
Highest Score
@pple