Variables and data types in Kotlin

- Andrés Cruz

En español
Variables and data types in Kotlin

In this next post about Kotlin we will talk about variables and data types in Kotlin; As we already know, Kotlin is a programming language that is much more useful for us than for Android since it uses the Java JVM virtual machine and we can use it in all kinds of developments, including with other Java developments as it is interoperable with this language.

As we have already discussed, Kotlin is concise by reducing the amount of code to write, versatile and light, since it can be used for Android and client-side language (browser) are some of the characteristics that describe it; In this post, we will talk about data types and their declaration.

Variables of two types: mutable (var) and immutable (val)

As in Java, Kotlin allows you to define variables of two types, immutable, which means that they cannot be modified (in Java we mark it as final) using the val keyword, and mutable, which means that they can be modified at any time, defined by the var keyword; let's look at the following series of examples.

Values inferred by the Kotlin compiler

We can define variables of either mutable and immutable types as follows:

var age = 27 // valor mutable

As we can see, in the previous line of code we indicated that we created a mutable variable named age with the integer numeric value of 27, but we did not explicitly indicate that it is an integer (int) based on the value set in the variable, either of immutable type:

val age = 27

Or mutable, as we indicated in the previous example (var age = 27).

Explicitly indicate the data type

We can also explicitly indicate the data type:

var age:Int

And explicitly specify the data type and define the data type:

var age:Int = 27

As we can see, there are plenty of options and they are adapted according to the needs.

Of course, we can declare other data types like Char, Boolean, String etc:

var name:String = "Andrés"

Of course, all the logic explained so far is maintained; that is, if it is mutable (var) and immutable (val), if the value is explicit or implicit, etc.

As you can see, the above definitions either inferring the type or not can be used with val.

Data types in Kotlin

Next let's look at the numeric data types in Kotlin:

TipoBit width

For the other types of data that are not numeric we have:

  • Boolean
  • Char
  • String

In the next entry that we discuss about Kotlin, we will give some illustrative examples about conversion (casting or converting from one data type to another) and comparison of one data type to another.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.