Open In App

What’s the Difference Between “const” and “val” in Kotlin?

Last Updated : 14 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Kotlin, as in other programming languages, properties can be mutable (changeable) or immutable (not changeable). To declare an immutable property, we utilize the terms const and val. Developers are frequently perplexed as to when to utilize one of these phrases. In this article, we will examine the distinction between const and val in Kotlin.

Use of “const” in Kotlin

The const keyword is used to declare properties that are immutable in nature, i.e. read-only properties. The values are only known on the compile-time though, as a result, no values may be assigned at runtime to const variables. To be a const property, a property must meet the following requirements: 

  1. Must be at the top level or a member of an object or a companion object.
  2. Should start from a primitive data-type
  3. No custom getter So, you can’t assign a const variable to a function or a class because the variable will be initialized at runtime rather than compile-time.

Use of “val” in Kotlin

The primary distinction between const and val is that val properties can also be initialized at runtime. As a result, you may assign a val variable to a method or a class.

Example:

Kotlin




const val gfgName = "Geeksforgeeks" // goes well
val coursename = "Android" // goes well
  
const val gfgName = getgfgName() // not goes well
val coursename = getcoursename() // goes well


The immutable variable in the above example is gfgName. When using const, directly assigning the value is OK; however, attempting to assign the value from some function getgfgname will result in an error since the value will be assigned at runtime rather than compile-time. However, in the case of val, both scenarios are acceptable.

Why use “const” when “val” will suffice?

We saw in the last example that the val variable’s value is initialized at runtime and const at compile time. So, why use const when val will suffice? Let’s look at another real-world Android example to see how const and val are used:

Kotlin




GeeksforGeeksClass {
    companion object {   
        const val IMAGE_EXTENSION = ".jpg"   
        val LOGONAME: String
        get() = "Geeks" + System.currentTimeMillis() + IMAGE_EXTENSION
    }
}


GeekTip: In the above example, we declare the const value IMAGE_EXTENSION in the companion object and initialise the FILENAME variable as val using a custom getter.

Because the file extension will always be the same, it is defined as a const variable. However, the file name will be modified based on the rationale we apply for the file name. In this example, we’re naming the file after the current time. You can’t give it a value at first since the value is obtained during runtime. So we’re going to use val here. 

Kotlin




public final String getIMAGENAME() {
   return "Geeks" + System.currentTimeMillis() + ".jpg";
}


In the above example, we declare the const value FILE EXTENSION in the companion object and initialize the FILENAME variable as val using a custom getter. Because the file extension will always be the same, it is defined as a const variable. However, the file name will be modified based on the rationale we apply for the file name. In this example, we’re naming the file after the current time. You can’t give it a value at first since the value is obtained during runtime. So we’re going to use val here.

Here, the variable IMAGE_EXTENSION has been replaced by its value, “.jpg,” indicating that the value has been inlined and therefore there is no overhead to access that variable at runtime. This is the benefit of using const instead of val.

Let us see the differences in a tabular form -:

  const val
1. It is a keyword that is used when we want a variable value to remain constant. It is a keyword that is used to declare a variable in kotlin.
2. It is only used to declare a read-only property of a class in kotlin. It is initialized at runtime.
3. Its value is known at compile time of the program. It cannot be assigned multiple times.
4. We cannot change the value of the variable that is declared constant.  It can be used with the const keyword.
5. It is used at the start of the variable declaration.

syntax -:

val variable_name= value



Similar Reads

Difference between var and val in Kotlin
var and val are both used to declare variables in Kotlin language. However, there are some key differences between them: VAR(Variable) It is a general variable. The value of a variable that is declared using var can be changed anytime throughout the program. var is also called mutable and non-final variable, as there value can be changed anytime. E
2 min read
Difference between html() text() and val() methods in jQuery
In this article, we are going to discuss the differences between html(), text(), and val() methods and their usage. 1. jQuery html() method: The html() method is used to set or return the inner HTML of a selected element. It works similarly to innerHTML in normal JavaScript to set or get the content of the selected element. The above code tells the
4 min read
Difference between Object.freeze() and const in JavaScript
ES6 has brought several new features and methods into JavaScript since its release. Amongst these new features are Object.freeze() method and const. Sometimes people get confused between Object.freeze() method and const but the Object.freeze() and const are completely different. In this article we will explain the differences between these two. Jav
3 min read
Difference between var, let and const keywords in JavaScript
In JavaScript, we use var, let, and const to create variables. These keywords might seem similar at first, but they control how and where your variables work in your code. Let's explore each one and how they differ from each other. JavaScript var keywordThe var is the oldest keyword to declare a variable in JavaScript. It has the Global scoped or f
5 min read
Difference between Kotlin and Scala
Scala may be a exceptionally multi-paradigm language that can run anyplace from being distant better than improved Java to a more regrettable Haskell. This implies that Scala libraries and codebases regularly utilize a assortment of distinctive coding styles, and learning to work with them all can take a long time. Plus it makes it harder to standa
3 min read
Difference between Java and Kotlin in Android with Examples
Kotlin KOTLIN is a cross platform, statically types, general purpose programming language with type inference. KOTLIN is designed to interoperate fully with java but type inference allows its syntax to be more concise.KOTLIN is sponsored by JetBrains and Google through the Kotlin Foundation. Java JAVA is an Object Oriented Programming Language deve
3 min read
Difference Between Flutter and Kotlin
Before, for cross-platform development Flutter and React Native were the go-to programming solutions and these languages were highly used by the developers. But today Kotlin has also become very popular and it has managed to enter the competition. So, the debate started that who will rule the market and which one will be more demanding for applicat
5 min read
Kotlin Exception Handling | try, catch, throw and finally
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program. There are two types of Exceptions - Checked Exceptio
6 min read
Kotlin Nested class and Inner class
Nested Class In Kotlin, you can define a class inside another class, which is known as a nested class. Nested classes have access to the members (fields and methods) of the outer class. Here is an example of a nested class in Kotlin: C/C++ Code class Car { var make: String var model: String var year: Int inner class Engine { var horsepower: Int = 0
5 min read
Kotlin Expression, Statement and Block
Kotlin Expression - An expression consists of variables, operators, methods calls etc that produce a single value. Like other language, Kotlin expression is building blocks of any program that are usually created to produce new value. Sometimes, it can be used to assign a value to a variable in a program. It is to be noted that an expression can co
4 min read
Kotlin | Default and Named argument
In most programming languages, we need to specify all the arguments that a function accepts while calling that function but in Kotlin, we need not specify all the arguments that a function accepts while calling that function so it is one of the most important features. We can get rid of this constraint and make parameter optional i.e pass an argume
7 min read
Kotlin Nested try block and multiple catch block
Nested try block - In this article, we are going to learn nested try-catch block and multiple catch block. Nested try block is a block in which we can implement one try catch block into another try catch block. The requirement of nested try-catch block arises when an exception occurs in the inner try-catch block is not handled by the inner catch bl
3 min read
Kotlin | Type Checking and Smart Casting
Type Checking - In Kotlin, we can check the type of certain variable using the is operator at runtime. It is a way of checking the type of a variable at runtime to separate the flow for different objects. Kotlin program of type checking using if-else blocks- C/C++ Code fun main(args: Array<String>) { var name = "Praveen&q
4 min read
Kotlin | Class Properties and Custom Accessors
The basic and most important idea of a class is Encapsulation. It is a property to encapsulate code and data, into a single entity. In Java, the data are stored in the fields and these are mostly private. So, accessor methods - a getter and a setter are provided to let the clients of the given class access the data. For sending notifications about
2 min read
Kotlin | Plus and minus Operators
In Kotlin, plus and minus operators are used to work with the list of objects which is usually referred to as Collections (List, Set, Maps). As the name suggests, plus operator adds up or concatenates the elements or objects of the given collections. The elements of the first collection remains as it is and the elements of second collection are add
2 min read
Top 10 Books to Learn and Master Kotlin
Do you want to learn Kotlin for Android app development or enhance your Kotlin skills? If yes, then you are on the right track. This article will cover all the Kotlin books that will help you learn Kotlin and increase your Kotlin knowledge. These books include basic concepts as well as advanced Kotlin concepts. Though before delving more into this,
7 min read
JvmStatic, JvmOverloads, and JvmField in Kotlin
In this article, we'll look at how to utilize Kotlin code in our current Java code using @JvmStatic, @JvmOverloads, and @JvmField in Kotlin. You may invoke Kotlin code from Java code and vice versa. This blog will concentrate on invoking Kotlin code from Java code. C/C++ Code // Kotlin Class class GeeksforGeeks // Calling from Kotlin val article =
3 min read
What is Flow in Kotlin and How to use it in Android Project?
To build an app asynchronously we have to use RxJava and it is also one of the most important topics in Android Development. But now in Kotlin Jetbrains came up with Flow API. With Flow in Kotlin now we can handle a stream of data sequentially. Flow is a stream processing API in Kotlin developed by JetBrains. It’s an implementation of the Reactive
4 min read
Returns, Jumps and Labels in Kotlin
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and a new language for the JVM. Kotlin is an object-oriented language, and a “better language” than Java, but still be fully interoperable
3 min read
Function Return and Type Hierarchy in Kotlin
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, App code, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a “better language” than Java, but still be fully interoper
4 min read
Login and Registration in Android using Firebase in Kotlin
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. In this article, we will learn the firebase authentication feature. Using it we can
4 min read
Unit Testing of ViewModel with Kotlin Coroutines and LiveData in Android
The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later. In this article, we will learn how to write a unit test for a Vie
4 min read
Subscript and Superscript a String in Android with Kotlin
In science, a scientific expression defining a context is a combination of a finite number of symbols according to the rules of the context. So in a basic sense, such expressions are formed by various writing styles or scripts such as lower case, upper case, symbols, numbers, subscripts, superscripts, etc. So in this article, we will show you how y
2 min read
Static Methods and Companion Objects in Kotlin
Unlike Java, Kotlin doesn't support static methods for a class. Most readers will know that static methods do not belong to the object instance but rather to the type itself. In Kotlin, it is advisable to define methods at the package level to achieve the functionality of static methods. Let's define a new Kotlin file and name it Static. Within thi
6 min read
Android - Swipe to Delete and Undo in RecyclerView with Kotlin
We have seen many android applications in which data is being displayed in the form of a list. If we want to delete any item from that recycler view we can simply swipe that item to delete it. We can see this type of feature in the Gmail application in which when an email is swiped to the right it is moved to the archive. In this article, we will b
7 min read
Android - Build a Movie App using Retrofit and MVVM Architecture with Kotlin
Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. The separate code layers of MVVM are: Model: This layer is responsible for the a
5 min read
How to Build a Food and Their Price List Android App using MVVM Architecture with Kotlin?
In this article, we will food app that displays a list of foods and their price using the retrofit library and MVVM architecture. Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from
5 min read
Android - Login and Logout Using Shared Preferences in Kotlin
Using Shared Preferences We can store data locally on our Android applications. In your Android app if you are using a feature of Login then you should have to save the state if the user has signed the first time. Then when the user closes his app and reopens it then he should redirect to our Home screen, rather than opening a login screen. So in t
6 min read
Kotlin Class and Objects
In Kotlin, classes and objects are used to represent objects in the real world. A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or fields), and implementations of behavior (member functions or methods). An object is an instance of a class and has its own state and behav
4 min read
Android Drag and Drop with Kotlin
In most Android applications where data is displayed in the form of a list format, there is a functionality with the help of which we can simply drag and drop any item from that list to any specific position within the list. To implement this type of drag-and-drop functionality we have to use a Drag Linear layout so that we can drag and drop items
5 min read