Ultimate Guide to Kotlin Variables Var vs Val Explained

Hello friends, This is the “Ultimate Guide to Kotlin variables”. In this tutorial, we will learn about Var and Val. We will be discussing the difference between Var and Val variables and mostly where we should use Var and Where we should use Val in Kotlin. So let’s get started.

From the beginning of programming language development, variables are crucial in software development. As in beginner language, “Variables are used as data containers which store different data type values”.

Ultimate Guide to Kotlin Variables Var vs Val Explained

Ultimate Guide to Kotlin Variables Var vs Val Explained:

1. Var(Mutable Variable):

A variable declared with var is mutable in Kotlin meaning its assigned value can be changed or reassigned multiple times throughout the program. It is very helpful for scenarios where data can be updated dynamically within the program. There are two different ways in Kotlin to declare a variable With Typecasting and Without Typecasting(also known as type interface).

Typecasting Var syntax:

Example:

Without Typecasting interface:

2. Val(Immutable Variable):

A variable declared with val is immutable, which means its value cannot be changed after it’s assigned. val is the same as the final variable in Java.

Typecasting val syntax:

Example:

Without Typecasting val syntax:

Happy reading.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *