Variable naming rules in Kotlin

The variable name you choose should explain exactly what the variable does. Let’s see in order the rules that you are advised to follow so that your code does not become complex and incomprehensible.

As you know, every variable must have a unique name. Although it may seem problem-free at first, as your software expands, your codes may become difficult to understand. Most of the software developers’ time is spent reading the code written by others, not writing code.

If you want the code you write to be easy to read and follow, it is very important to follow the naming rules. The variable name you choose should explain exactly what the variable does. Let’s see in order the rules that you are advised to follow so that your code does not become complex and incomprehensible.

Mandatory Naming Rules

  • Names are case sensitive. (number and Number are not the same expression.)

  • Names must consist only of letters, numbers and underscores.

  • Names cannot have a number at the beginning (1month is the wrong usage.)

  • Keywords that the Kotlin software reserves for itself (val, var, fun, etc.) cannot be used as variable names.

  • If a variable name consists of a single word, it must be written in all lowercase letters. (name, message)

  • If a variable name consists of more than one word, lowercase Camel style notation should be used. (numberOfStudents, numberOfPages). As can be seen, after the entire first word is written in lowercase, only the first letter of each word should be capitalized.

  • Although it is not prohibited, you should not start the variable name with an underscore _.

  • You must give meaningful names to the variable. As a variable name, the color name will be more descriptive and meaningful than the c expression.

Magic Numbers

In the example command below, the number 7 is written to the screen. It is very difficult for another programmer reading this program to know what the number 7 is. In such cases, numbers should be named using const and used that way, even if they are a constant. When naming, the UPPERCASE_LETTER_SNAKE type should be used. This usage will provide great convenience to understand the code.

Not Recommended Use

fun main() {
    println(7)
}
/* Output
7

Process finished with exit code 0
 */```



Recommended Use


```kotlin
const val DAYS_OF_THE_WEEK = 7

fun main() {
    println(DAYS_OF_THE_WEEK)
}
/* Output
7

Process finished with exit code 0
 */```



If you follow the rules we explained above as much as possible, it will be very helpful and save time for both you and your friends who will be involved in the project later.

Comment Lines in Kotlin Programming

Comment lines are not taken into account by program compilers and are not included in the process. There are 3 different types of comment lines in Kotlin.

A computer program consists of various pieces of code coming together and working in harmony. Each block of code does what is expected of it. As time goes on, the program developers who write these codes begin to forget and get confused about which code does what. In addition, a new developer who replaces the developer who left the project must learn the program by reading the codes. In this case, explanations, notes and similar expressions written next to the codes are called comment lines.

Comment lines are not taken into account by program compilers and are not included in the process. There are 3 different types of comment lines in Kotlin.

End of Line Comments

These are comments that do not exceed one line in length. They are written after the // sign. Everything after the // sign and up to the end of the line is considered a comment. The example below shows the comment lines used with //.

fun main() {
    val name: String = "John"
    //identifier =name , Type = String, initialization = John
    var age: Int = 16
    //identifier =age , Type = Int, initialization = 16
    println(name)
    println(age)
}

Multi-Line Comments

All comments starting with the /* sign and ending with the / sign, regardless of how many lines there are, are considered comments. It is ignored by the compiler. You can use the / Comment */ format for single-line or multi-line comments. Below is an example of a multi-line comment.

fun main() {
    val name: String = "John"
    /* 
    identifier =name , Type = String, initialization = John
    identifier =age , Type = Int, initialization = 16 
    */
    var age: Int = 16

    println(name)
    println(age)
}

Documentation Comments

Preparing a user guide about our software, adding copyright statements, etc. These are comments written between /** and */ for the following purposes. An * sign is also placed on each line. You can create documentation by compiling the comments you write in this format through another software. Below is an example of a documentation comment.

/**
 * Copyright siberoloji.com 2024 MIT license
 * main() function declares 2 variables with standard assignment template.
 * We can omit Type here because it is redundant.
 * Kotlin decides the type of variable with "Type Inference"
 */

fun main() {
    val name: String = "John"
    /*
    identifier =name , Type = String, initialization = John
    identifier =age , Type = Int, initialization = 16
    */
    var age: Int = 16

    println(name)
    println(age)
}

We can use comment lines to test some codes. We can put the codes we want to cancel during the experiment in the comment line instead of deleting and retyping them. There are also some ways to use less comment lines. For example, giving variable names more meaningful will make the written code more readable. We will explain this issue in another article.

Kotlin value assignment and type inference

In this article, we will explain some of the finer points you need to know about defining variables in the Kotlin programming language.

In this article, we will explain some of the finer points you need to know about defining variables in the Kotlin programming language. We have prepared this article in addition to the rules we explained in our previous two articles ("Kotlin Variable and Value definition", “Constants and variables in Kotlin”).

We all know that numbers and letters are different types. While mathematical operations can be performed with numbers, mathematical operations cannot be performed with texts. We should note that this distinction also exists in programming languages. Therefore, every variable must have a type.

The variable definition template in the Kotlin programming language is as follows.

val/var identifier: Type = initialization
  • At the very beginning is the expression val or var. Val or var selection is made depending on the behavior of the value of the variable. We explained the differences in our article titled “Kotlin Variable and Value Definition”.

  • identifier: So it should be the name of the variable. Choosing a name that is meaningful and explains what it does to avoid confusion with other variables will always be beneficial.

  • Type: We write the type of the variable here. Expressions that express the type of the value, such as String, Int, Boolean, start with a capital letter. Type is written after writing a colon after the name of the variable.

  • Initialization: We assign the initial value to our variable. It means initial value. When the type of the variable is determined, the initial value does not have to be assigned immediately. We will give examples of correct and incorrect usage below.

Now let’s write an example according to this template. The example below has a structure that fulfills all the rules completely.

fun main() {
    val name: String = "John"
    //identifier =name , Type = String, initialization = John
    var age: Int = 16
    //identifier =age , Type = Int, initialization = 16
    println(name)
    println(age)
}
John
16

Process finished with exit code 0```



## Determining the Data Type (type inference)



If we determine its initial value (initializer) when we define a variable, we may not write the data type. Kotlin will detect its type by looking at the first value entered. In this way, our codes become simpler. The example is below. 


```kotlin
fun main() {
    val name= "John"
    //identifier =name , initialization = John
    var age= 16
    //identifier =age , initialization = 16
  
    println(name::class.simpleName)
    println(age::class.simpleName)
}

/* Expected Output
String
Int

Process finished with exit code 0
*/```



As seen in the example above, Kotlin automatically determined the data type by looking at the type of the initial values even though the data types were not entered. When you examine the subject from foreign sources, you can see that this process is referred to as "type inference".



## Defining a Variable Without Initial Value



If you want to define a variable but determine its initial value later, you must write the type of the variable. Kotlin cannot determine the type of the variable without the initial value. When a variable is defined for Kotlin, its type must also be determined. The type cannot be changed later. You can see an example of this below.


```kotlin
fun main() {
    val name: String
    //identifier =name , Type = String
    var age: Int
    //identifier =age , Type
    name = "John"
    age = 16
}

As seen in the example, the variable name and type are determined, but the initial value is determined elsewhere. This usage is correct. If the initial value is determined at another time, it is necessary to write the variable type.

Incorrect variable definition

Defining a variable without both a data type and an initial value will cause you to encounter an error. The usage below is incorrect. Your program will not compile.

fun main() {
    val name //error
    name = "John"
   
    var age //error
    age = 16
}

Constants and variables in Kotlin

We introduced the topic of defining variables and assigning values in the Kotlin programming language in our previous article. In this article, we will take a closer look at assigning values with const and val.

We introduced the topic of defining variables and assigning values in the Kotlin programming language in our previous article. In this article, we will take a closer look at assigning values with const and val.

val variables

The code below defines two variables, an integer containing the constant number pi and a String value named helloMsg. These values cannot be changed again after they are first assigned.

fun main() {
    val pi = 3.1415
    val helloMsg = "Hello"

    println(pi)       // 3.1415
    println(helloMsg) // Hello
}

Let’s try to assign a new value to the pi variable, which is defined with the val keyword and assigned its initial value. As seen in the example below, when we want to assign a new value to the number pi, you receive the error “Val cannot be reassigned”.

fun main() {
val pi = 3.1415
val helloMsg = "Hello"

println(pi) // 3.1415
println(helloMsg) // Hello

pi = 3.1416 // Val cannot be reassigned
}

You cannot use a variable that is defined with val but has not been initialized, that is, has not been initialized, in your commands. Let’s explain this with an example. With the code below, the variable named boolFalse is defined with val, but since its initial value (True or False) is not assigned even though its type is specified as Boolean, you will receive the error message “Variable ‘boolFalse’ must be initialized”.

val boolFalse: Boolean
println(boolFalse) // error line```



Correct usage should be as follows.


```kotlin
val boolFalse: Boolean // not initialized
    boolFalse = false      // initialized
    println(boolFalse)     // no errors here```



## const variables



In Kotlin programming, there is a constant value assignment method in which the `const` keyword and the `val` expression are defined together. With this method, the constant value is created when the program codes are compiled and cannot be changed again. As a rule, it is recommended that the names of variables defined as `const` be in all CAPITAL LETTERS. 


```kotlin
const val WRITER_NAME = "JOHN DOE"```



There are some rules for defining a constant value in this way.


* 
* Only String and INT, CHAR, DOUBLE, BOOLEAN data types, which we call primary types, can be assigned to constant values. An example of this is shown below.

* Constants should be defined outside functions. They cannot be defined with a const statement within a function.



```kotlin
const val CONST_INT = 256
const val CONST_DOUBLE = 3.14
const val CONST_CHAR = 'f'
const val CONST_STRING = "I am constant"
const val CONST_ARRAY = arrayOf(1, 2, 3) // error: only primitives and strings are allowed
fun main() {
    println(CONST_INT)
    println(CONST_STRING)

}

These explanations and rules may seem a bit confusing at first. Remember that these are necessary for the written code to work correctly and without errors. As you practice, you will become more familiar with these rules.

Kotlin Variable and Value definition

Variables are almost the most important building blocks in programming.

What is a variable?

A variable is a record location in which a number, text or any other information is kept. Variables are almost the most important building blocks in programming. There are variables in which these values are kept in all the operations we will perform. We call its name “variable” because the value stored in it can be changed.

For example, consider a school and the classes within it. We should record the name of each class somewhere and the number of students in each class somewhere. Each variable must have a name (identifier) to distinguish it from other variables. In this case, we will have two variables that we will refer to as “class name” and “number of students”.

variable definition

In the program we will write, we must have defined the variable before we can use it. Kotlin offers two keywords to define variables. The variable names should not start with a number and it should be noted that they are case sensitive.

val (value)

The variables we define with the val expression are variable types in which the value does not change again after a value is assigned at the beginning of the program. For example, we can give the name of a Novel we want to transact with. Even if the number of pages changes as a result of different printing styles, the name of the author and the title of the novel will remain constant. However, this requires a fixed author name and book name for another book. Because of this need, we will define variables with the val expression, which we can assign the desired value to once during the first run of the program but cannot change later.

The contents of such variables are determined at run time.

fun main() {
val language = "Kotlin"
    println(language)
}

/* Output
Kotlin

Process finished with exit code 0
 */```



In the example above, a variable named `language` is defined and its value is assigned with `=` to `"Kotlin"` of type **String**. You should note that the `=` sign is used to assign the value. Now we can call this variable "language" while writing our codes in the program.



var (variable)



It is a type of variable that we can change the value stored in as much as and whenever we want. We can express it as a changeable variable.


```kotlin
fun main() {
    var dayOfWeek = "Monday"
    println(dayOfWeek) // prints Monday
    dayOfWeek = "Sunday" // new value is Sunday
    println(dayOfWeek) // prints Sunday
}

/* Output
Monday
Sunday

Process finished with exit code 0
 */```



As you can see in the example above, we first gave the `dayOfWeek` variable the value `Monday` and printed it on the screen. Then, we gave the value Sunday and printed the new value on the screen. In this way, we used a variable by changing the values in it.



const (constant)



Values that are known while the program is being coded and will not change no matter who uses the software are called constants. Constants also need to be recorded somewhere. For this reason, constant values are assigned by using the const expression together with the val expression.



The contents of such variables are determined at compile time.



Assigning data in different value types



You can define as many variables as you want to store different data types in Kotlin. You can see an example of this below.


```kotlin
fun main() {
    val ten = 10
    val greeting = "Hello"
    val firstLetter = 'A'

    println(ten) // prints 10
    println(greeting) // prints Hello
    println(firstLetter) // prints A
}

/* Output
10
Hello
A

Process finished with exit code 0
 */```



There is an important rule we need to point out here. For example, if we assume that you first assign an **Int**, that is, integer value to a variable using var (`val ten = 10`), the values we assign to that variable from now on must always be integers. Whatever the first data type was assigned, the data type to be assigned later must always be the same.



## Conclusion



We now know that the keywords `val` and `var` are used to define variables, that variable names must start with a letter, and that variables can only be assigned to the value type they were first assigned to. This information will be very useful for the next stages.

Basic Literals in Kotlin

No matter how complicated, all programming languages perform operations on integers, characters, strings, etc. performed on values. We call these values Literal expressions

No matter how complicated, all programming languages perform operations on integers, characters, strings, etc. performed on values. We call these values Literal expressions. It would be very appropriate to explain these types before starting to write a program. These are integers, characters, and strings.

Integers

We constantly use integers to count things in our daily lives and in mathematics. The same integers are also used in Kotlin. All the numbers you see below are integers. For example; 0, 1, 2, 10, 11, 100 If an integer contains many digits, we can split the integer into blocks using _ (underscore) to make it easier to read and understand. For example; Instead of 1000000, we can write it as 1_000_000. This means the same integer for both Kotlins. As long as the underscore is not at the beginning or end of the numbers, it can be used as desired. 1__000_000 , 1_2_3 These expressions are also true. An error occurs when you type 10 or 100.

Characters

A single number, font and space, * - etc. It is a data type used to represent some special characters. The first thing to consider here is that there should be a single character. Characters are written in single quotes ’ ’ as seen below. ‘A’, ‘a’, ‘x’, ‘y’, ‘2’, ‘8’, ‘*’, ’ ‘, ‘$’ all these expressions are called characters. Since the character data type can contain a single expression, the following expressions are incorrect even if enclosed in single quotes. ‘abc’, ‘543’

Strings

They are character strings formed by the combination of one or more characters. Unlike characters, they are shown in double quotes “ “. Below you can find a few correct usage examples. Any desired character, including the space character, can be used within double quotes. “Text”, “I want to learn Kotlin”, “123 456”, “email@email.com” You should note that a character string can also contain a single character. “A” - It is a string because it is written in double quotes. ‘A’ - It is a character because it is written in single quotes.

Conclusion

Apart from the 3 different data types explained above, there are other data types in Kotlin. We will explain those further when appropriate. These 3 data types will be enough to start with to explain basic commands and operations.

First Kotlin Program Hello World

When starting to learn programming languages, we always start with the same example. Let’s start our Kotlin programming article with the “Hello World” program without breaking tradition.

When starting to learn programming languages, we always start with the same example. Let’s start our Kotlin programming article with the “Hello World” program without breaking tradition.

You can copy the code you see below and paste it into your editor, or you can go to the “Kotlin Playground” page via your Web browser and try the codes there.

// First program in kotlin
fun main() {
    println("Hello World")
}

Explanation:

The line that starts with the // sign is the comment line. The compiler does not accept this line as code. It is used to take notes or make explanations about which code does what.

The fun expression refers to the beginning of a function.

main() is the entry point of Kotlin programs. It is case sensitive.

A code block is written between { } signs.

println("Hello World") is a code expression you see here. When we send the “Hello World” parameter to the println() function, it will write the sent parameter to the screen and move to the next line. If you want, you can print more than one line under each other. Here is an example.

// First program in kotlin
fun main() {
    println("Hello World")
    println("I am the first Kotlin Program")
}

When we run the example above, you should get the following output.

Hello World
I am the first Kotlin Program

Process finished with exit code 0```