The only thing CONSTANT in life is CHANGE (or Variables). Regardless of their TYPE.

When we talk about programming, almost all languages use variables and constants to store information in a very similar way. We use variables to store data and pass information around in the program. You can think of a variable as a container that will hold something you will put inside of it to be used later. One particular thing you should keep in mind about most of these containers is that they will hold only one type of thing. There are some exceptions but I’ll talk about them in other posts.

So imagine you bought a bunch of Ikea organizers to store your winter things. One box will hold your socks, one will hold your winter hats and one will hold your scarves and you cannot mix them up. These things (socks, winter hats and scarves) are the data types or the type of things (information) you will put inside each of the boxes (variables or constants).

How to declare a variable

Declaring a variable in Kotlin is as simple as this: val name = Rosie

You don’t need anything other than that. You can determine the variable type (and in some cases, you will need to) but Kotlin also has a feature called type inference and it “guesses” the data type of a variable based on the value you assign to it. So, to better illustrate that, I will add the data type below.

The first element in the image is the Variable definition keyword which will define if the variable you are declaring (creating) is mutable (var) or immutable (val). Then comes the variable name which in this case I named it name but it can be anything you want. Preferably something that will make sense to other people reading your code and also for future you. So try to create meaningful names that actually say something about the information they are holding. But you can name your variables after snacks if you want. Will you know what they mean a few weeks from now or even a few hours? NO. But the bottom line is you can if you want to.

Variable names should follow the camel case practice which consists in starting the name of the variable with a lowercase letter and then if it is formed by more than one word you capitalize the first letter of the following words like this camelCase. So, if my variable name was referring to the first name and last name information, I would use
val firstName = "Rosie" and val lastName = "M"

Please note this is how it’s done in Kotlin. Other languages have their own way of declaring variables that are similar but not exactly the same.

In Java, for example, the same variable would read String name = "Rosie";
In PHP it would be $name= "Rosie" 

Mutable vs Immutable variables

Sometimes you will need to have a variable that can have its value reassigned (changed). For example, if you create a variable to track a score of a game it will need to change when each time or player scores another point. So, in this case, you need a mutable variable which in Kotlin you can do by giving the variable the var key. So your score variable would look like this:

var homeScore = 0 and var visitorScore = 0

That said, you will often need to have a variable where the assigned value should not be changed and Kotlin provides a different way of declaring immutable (aka read-only) variables (I want to say they cannot be changed, but that’s not 100% true. There’s a way of doing that using classes, get and set methods but let’s leave that for another post). For example, if you prompt the user to input their name, or to create a new character in a game and give it a name that won’t be changed later, you can use the key val as used in the image above.

If you try to reassign the value of a val you will get the squiggly red line and a notice saying its value cannot be reassigned.

Read-only variables (vals) are used to prevent accidentally changing variables that should not be changed, so, usually, the best thing to do is to use vals all over and change them to var only if you need to. If you are using IntelliJ or Android Studio, for example, they can detect when the change can be made and it will suggest that you convert it from val to var and vice-versa.

Type inference

Another nice feature Kotlin has is Type Inference. This allows you to omit the data type of a variable that has a value assigned to it. Sometimes you need to create a variable and don’t initialize it (don’t assign a value to it) and in this case, you need to establish the data type you want that variable to have, but if you give it a value, Kotlin automatically infers the type for you.

Note the image above. I did not mention that name was a String, but if you hover over it:

You can see that the type String is properly assigned to it. On the other hand, if you do specify the type, the IDE tells you that it’s not needed:

Basic Data Types

As you can see from the image above, the variable we declared is a String. This is the variable’s type. If you would change the code to val name: String = 32 you will see the infamous squiggly red line under the value assigned to the variable name and if you hover the mouse over it you can see the message telling you to change the variable type from String to Int

Kotlin uses a static type system which means the compiler defines specific types to the variables you create so it can make sure the code you wrote is valid. It also means that once you define a type for a variable it cannot be changed. So if you declare a variable of type String you cannot turn it into an Int later.

The most used types in Kotlin are:

TypeWhat does it holdExample
StringText in general “Rosie”, “This is an example of a String”
CharSingle Character‘A’, ‘a’, ‘n’
IntWhole numbers0, 1, -10
DoubleDecimal numbers3.14159, 5.2,
Long64-bit numbers, meaning numbers that are too long to be an Int9,223,372,036,854,775,808
BooleanTrue or false valuesTrue, false
ListsA collection of elements1, 2, 2, 45, 12, 88
“Rosie”, “Harry”, “Daniel”
MapsA collection of pairs“Rosie” to 1, “Harry” to 2…

Constants

Constants, also known as Compile-time constants, are variables that are used for absolute values. Let’s say your app calculates the area of circles. The formula to calculate the area of a circle is A = πr² (Area is equal to Pi times the radius squared). Pi is a known number. It can be used with a different number of decimals but it’s a known, existing number. So you can establish Pi as a Compile-time constant like this: const val PI = 3.14159 or
const val PI = 3.14 and here you determine how many decimals will be used in your formula.

A compile-time constant is defined outside of a function, including the main function because its value must be determined at compile time (hence the name) and functions (including main) are called during runtime. When you add the const modifier to the variable you are telling the compiler that no matter what happened, that information will stay the same. It cannot be changed and that allows the compiler to perform some optimization behind the scenes.

They can be one of these types:

  • String
  • Int
  • Double
  • Float
  • Long
  • Short
  • Byte
  • Char
  • Boolean

Another thing to note about constants is that the camel case practice does not apply here. For constants, we use what is called SNAKE_CASE (all caps and words are separated by an underscore).

Published by Rosie M

Android bug creator and full-time nerd. Joined Automattic in 2017. Passionate about music, books, games, photography and Doctor Who. Open-source enthusiast, remote-work advocate and Globetrotter.

3 thoughts on “The only thing CONSTANT in life is CHANGE (or Variables). Regardless of their TYPE.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: