Apps/Gaming

Difference between var, val and const in Kotlin

If you’ve ever worked with Java (and version-specifically), you might have noticed that the language didn’t have a keyword to explicitly declare a variable – until version 10 was released, where Java developers started doing something like to have the following example:

var name = “David”;

Before that, the only way to declare a variable was to provide its type before its name, as shown here:

string name = “David”;

Since its conception, Kotlin has “concerned” about some of these Java language gaps and tried to provide a much simpler, less verbose and more intuitive programming experience.

Just like Java 10’s var keyword, Kotlin gives us the same ability to enable automatic type inference without having to explicitly tell the code what type it is. In this article, we’ll dig a little deeper into this keyword, as well as the other two ways of declaring variables and constants in Kotlin.

Read: Introduction to Kotlin

Enter inference in Kotlin

Kotlin was born with derived typing, while Java grew to a point where it had to allow it alongside the previous explicit style of type declaration. But what does that mean in practice? Let’s look at the previous example again:

var name = “David”;

This is where both languages ​​take action behind the scenes to deduce that the type of this name is a string, since the value assigned to it is very unique. Because the var keyword tells the language that it’s a variable, you can guess whether it accepts a variable that’s nullable (that is, it’s optional and accepts null values) or not.

In Java, if no value is specified, depending on the scope in which the variable is defined, the variable will either be initialized to its default value (every primitive type has one, objects default to null) or throw a compile-time error indicating this need .

For example, take the following code snippet in Java:

string name; void print() { string name; System.out.println(name); // error: variable name may not have been initialized System.out.println(this.name); // outputs zero }

The above is a good example showing how a local and a global variable work differently in terms of default values ​​and compilation errors without initialization.

However, when dealing with the var keyword, this example cannot be applied because it is only valid for local scopes and requires the initialization of the variable:

void print() { var name; // error: cannot infer type for local variable name System.out.println(name); }

The same code from the previous example could be translated into Kotlin code as follows:

variable name: string? = null fun print() { var name // This variable must either have a type annotation or be initialized println(name) println(this.name) }

The first thing to notice in the examples above is how different the global variable is in Kotlin. By default, Kotlin does not allow nullable types like Java does. Instead, if you’re willing to make a variable optional, you need to say so explicitly by specifying its type, followed by a question mark (?) and its default value — yes, a variable can be declared to accept null values, but is also initialized with another one, as shown here:

variable name: string? = “”

The same rule applies to every single place you create variables, including local ones, as you could see from the error thrown by the internal name var. After we updated the code to be fully compileable as shown below, the expected results are printed:

variable name: string? = “David” fun print() { var name: String? = null println(name) // prints null println(this.name) // prints David }

Read: Getting started with Kotlin coroutines

Read-only values ​​in Kotlin

Just like in Java, constants are necessary for various purposes. To define that a variable is read-only, we previously had to explicitly add the final keyword to it:

final string name = “”;

As a result, the compiler immediately asks for a value to initialize, whether it comes from the constructor or is assigned directly.

The same applies to Kotlin, but with a val. The val keyword is a shortcut that leads to the same behavior but with much less verbosity:

value name = “”;

Note that type inference also takes place for val, which means that the type is optional in this case. These types of values ​​are very useful when creating data classes that handle immutability in Kotlin:

Data class Person (value name: string, value age: int?)

As observant developers may have noticed, you can also take null values ​​in the same way—they can be initialized to hold a constant null value:

Person(“David”, null)

Read: Best Java IDEs for 2022

Constants in Kotlin

Finally we have the constants. Wait, didn’t we just see constant values ​​in Kotlin? Yes, somehow – but with one difference. Just like in Java, if you want a constant to be known at compile time and available statically everywhere, developers need to add one more keyword: static:

Static final string NAME = “David”;

The convention also dictates that constants in Java must be uppercase. In Kotlin, constants follow the same principle, but their declaration is simplified, as shown below:

const val NAME = “David”;

Yes, the val keyword is required alongside const, and type inference is done the same way as before. Constants can also use the visibility access methods, just like in Java:

private constant value NAME = “David”;

In this case, the constant would only be available to the Kotlin file context in which it was declared.

Conclusion on var, val and const in Kotlin

This was a very brief but essential look at how the var, val, and const keywords work in Kotlin and how Java developers in particular can easily understand their usage as they are the basis of pretty much any coding you might want in make of the language.

Continue reading Tutorials and guides for Java programming.

Related posts

Python and HTTPS Client Development

TechLifely

Understanding Memory Leaks in Java

TechLifely

Traditional security vs. cloud security overview

TechLifely

Leave a Comment