Variables and data types in Kotlin

Video thumbnail

We'll talk about variables and data types in Kotlin, and we'll also give you a Hello World in this programming language. As we know, Kotlin is a programming language that serves us for much more than just Android, since it uses the Java Virtual Machine (JVM) and we can use it in all kinds of development, even with other developments in Java, as it is interoperable with this language.

Kotlin is concise by reducing the amount of code to write, versatile, and lightweight, as it can be used for Android and client-side (browser) language are some of the characteristics that describe it. In this post, we'll talk about data types and their declaration.

Let's continue and learn the basics of Kotlin, the programming language we'll use to develop our Android applications.

Remember we left off at the installation of Android Studio. For now, we can leave it as is; we won't need it immediately, and we'll finish configuring it later. The idea now is to focus on the basics of Kotlin, while you can go ahead and download the necessary packages and practice.

To start, we access the official website: kotlin.org. We click on Get Started and begin the tour. On this page, we'll see classifications and concepts that we will follow during the course, starting with the classic Hello World and the basic types.

The Famous "Hello World" and the main() Function

Just like with many programming languages (such as Python, Java, Dart, and obviously Kotlin), especially those intended for desktop or mobile applications that need a starting point, we have a main() function.

The main() function is the startup function. It's the first code that runs, hence its name, main or principal. It's the point where everything begins. You can have the most sophisticated application in the world, but if it doesn't have a starting point, it won't work.

In web applications, this changes a bit since access is given by routes (although in languages like PHP, we always have an entry file like index.php). In Kotlin, instead of an entry file, it's a function, as you can see.

  • main is the main function from which everything starts.
  • In web applications, like PHP, this would be equivalent to index.php, but in Kotlin, it's done through a function.

To execute the code, we simply click on the Run icon on the Kotlin website. This allows us to test our programs without needing to open Android Studio.

Function Declaration

In Kotlin, functions are defined using fun, followed by the function name and parentheses, and then curly braces to encapsulate the code:

fun main() { 
  println("Hello Kotlin") 
}
  • println() prints text to the console, adding a new line.
  • You can use print() to print on the same line.

Example of print():

fun main() { 
  print("Hello Kotlin") print("Let's keep going!") 
} 
// Output: Hello KotlinLet's keep going! (All on one line) Example of println():
fun main() { 
  println("Hello Kotlin") 
  println("Let's keep going!") 
} 
// Output: 
// Hello Kotlin 
// Let's keep going! (Each on a separate line)

The semicolon (;) is optional in Kotlin, just like in Python and JavaScript.

Thus, our first Hello World is simple and functional.

Basic Data Types

Kotlin has several data types:

  • Integers: Int, Long, Byte, etc.
  • Floating-point: Float, Double
  • Booleans: Boolean (true or false)
  • Characters: Char
  • Strings: String

It also includes unsigned integers, useful for identifiers or ages. The syntax is clear and consistent, which avoids common errors in other languages.

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

TypeBit width
Double64
Float32
Long64
Int32
Short16
Byte8

For the other non-numeric data types, we have:

  • Boolean
  • Char
  • String

In summary:

  • Integers:
    • Byte, Short, Int, Long: Used for whole numbers without decimals, and each defines the length (the range of numbers it can store). For example, Int can be used for an age or a size. Long is used when a lot of length is needed.
    • Unsigned Integers (e.g., UInt): These are positive integer types. They are extremely useful in many cases, such as database identifiers or for age, where we don't need negative values.
  • Floating-point:
    • Float and Double: Used for numbers with decimals.
  • Other Types:
    • Boolean: Can only be true or false. It's essential.
    • Char: Used for a single character.
    • String: Used for text strings, like the one we presented earlier in the "Hello World".

Kotlin features a highly structured type system, which is very beneficial.

Variables and Constants: Mutable (var) and Immutable (val)

Just like in Java, Kotlin allows you to define two types of variables: immutable, which means they cannot be modified (in Java we mark them as final) using the reserved word val, and mutable, which means they can be modified at any time, defined using the reserved word var. Let's look at the following series of examples.

Values Inferred by the Kotlin Compiler

We can define variables, whether mutable or immutable, in the following way:

var age = 27 // mutable value

As we can see, in the previous line of code, we indicate that we are creating a mutable variable named age with the integer numerical value of 27, but we don't explicitly indicate the type. Kotlin infers that it is of type integer (Int) based on the value set for the variable, whether it is an immutable type:

val age = 27

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

In summary:

Kotlin distinguishes between mutable and immutable variables:

  • val: constant, cannot change its value once assigned.
  • var: mutable variable, can be updated multiple times.

Example:

val constant = 5 
var variable = 3 
variable = 7
  • Using val whenever possible improves code efficiency and safety.
  • Uninitialized variables generate errors, thanks to Kotlin's null safety system.

This avoids common issues in other languages like JavaScript or Java, where code might execute with uninitialized variables.

In Kotlin, interesting concepts are introduced, such as null safety and the distinction between mutable and immutable types, which are equivalent to variables and constants but implemented directly in the language.

val (Immutable Value / Constant)

It is declared with the keyword val. The value of val cannot be reassigned or changed after its initialization. It behaves like a constant.

val a: Int = 3 // Initialized and declared 
val b = 5      // Initialized and the type is inferred (Int) 
a = 4 // This would result in an error

var (Mutable Variable)

It is declared with the keyword var. The value of var can be updated at any time. It behaves like a typical variable.

var d: Int = 3 // Declared and initialized d = 5

You can also explicitly declare the variable's type for greater clarity. This is done by placing a colon : followed by the type (for example, var d: Int).

Explicitly Indicating 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, the options are abundant and adapt according to the needs.

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

var name:String = "Andrés"

Naturally, all the logic explained so far is maintained; that is, whether it's mutable (var) or immutable (val), whether the value is explicit or implicit, etc.

As you can tell, the previous definitions, whether inferring the type or not, can be used with val.

Mutable/var vs Immutable/val

Although var allows greater flexibility, the recommendation in Kotlin (and other modern languages) is to use val (immutable) whenever possible. This is due to several advantages:

  • Efficiency (Optimization): Immutable values are more efficient because the compiler knows they won't change.
  • Less Prone to Errors (Bugs): If a value should not change, declaring it as val ensures that if you try to change it by mistake, the application will crash immediately, indicating the problem. If you use var and accidentally update it, it could cause a subtle and difficult-to-detect error later on.
  • Easier Reasoning: When seeing a val, anyone (including yourself a month from now) knows that this value remains fixed during the program's flow, making the code easier to understand.
  • Safety (Thread-Safe): Immutable values are safe in concurrency (multi-threading) environments, which contributes to the program's efficiency and optimization.

Use val by default, and only use var if the value genuinely needs to be mutable. This is one of the foundations of Kotlin as a modern language.

Operators and Comments

Kotlin supports the typical operators:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus (Remainder): %

Example:

var a = 5 var b = 3 
println(a + b) // Prints 8 
Addition	d = d + 1	d += 1 
Subtraction	d = d - 1	d -= 1 
Multiplication	d = d * 5	d *= 5 
Division	d = d / 2	d /= 2

Adding Comments

Comments are defined with the double forward slash //. The text that follows this on that line will not be executed by the compiler.

Kotlin

// This is a comment

Or multi-line:

/* * Comment * */

Conclusion

In summary:

  • We learned how to run Kotlin without Android Studio.
  • We created our first Hello World.
  • We looked at data types, mutable (var), and immutable (val) variables.
  • We learned how to print data to the console and use basic operators.

Kotlin is modern, safe, and expressive, incorporating best practices from its design. This makes the code more efficient and less prone to errors.

In the next post we will discuss Null Safety: Non-null types and nullability in Kotlin

It discusses the types: mutable (var) and immutable (val) in Kotlin, as well as numeric, String, and boolean data types, explicitly or implicitly indicating data types in Kotlin, mathematical operators, and a Hello World program.

I agree to receive announcements of interest about this Blog.

Andrés Cruz

ES En español