As you already know, every variable has a unique name that identifies it. Giving names to variables may seem easy. Alas, it is not true. Experienced programmers choose names for variables in their code very carefully, so their programs are easy to understand. It is so important because programmers spend a lot of time reading code written by others. Trust me, even your own code will become unreadable after a while if variables have bad names.
How to avoid this? Well, always give descriptive and concise names to all variables. I promise you and other programmers will enjoy reading such code for a long time.
Also, there are two sets of rules that restrict the possible names for variables.
Kotlin has some rules:
- names are case-sensitive (the
numbername is not the same as
- a name consists of letters, digits, and underscores;
- a name cannot start with a digit;
- a name must not be a keyword (for example,
funare illegal names).
Based on these rules, you may conclude that whitespaces are not allowed to enter the name of a variable.
Do not break these rules; otherwise, your program will not work.
Here are some valid names of variables:
score, level, fruitType, i, j, abc, _cost, number1
Now take a look at some incorrect ones:
@pple, 1number, !ab, val, var
Also, there are the following conventions:
- if a variable name is a single word, it should be in lowercase (for instance:
- if a variable name includes multiple words, it should be in
lowerCamelCase, i.e. the first word should be in lowercase and all the other words start with a capital letter (for instance:
- variable names should not start with
_characters, although it is allowed
- a name should make sense (for instance:
scoremakes more sense than
s, although they are both valid).
These conventions are optional, but it is strongly recommended following them. As we said before, they help you write more readable code.