МагазинНовостиПравилаПомощьДокументацияПрисоединиться

Naming variables

Why is naming important?

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.

Rules for naming variables

Kotlin has some rules:

  • names are case-sensitive (the number name is not the same as Number);
  • a name consists of letters, digits, and underscores;
  • a name cannot start with a digit;
  • a name must not be a keyword (for example, val, var, fun are 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

Conventions for naming variables

Also, there are the following conventions:

  • if a variable name is a single word, it should be in lowercase (for instance: number, value)
  • 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: numberOfCoins)
  • variable names should not start with _ characters, although it is allowed
  • a name should make sense (for instance: score makes 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.