If you’re new to Kotlin, you might be wondering what is need of const val when we have val? 🤔
Both are the same, Right? 🤔
Then this article is for you. 😄
- The main difference between val and const val is that val can be assigned a value at runtime, whereas const val must be assigned a value at compile time and cannot be changed afterward(their values are hardcoded).
/*
const val eg.
*/
const val baseUrl = "https://rickandmortyapi.com/api"
/*
val eg.
*/
val db = FirebaseDatabase.getInstance()
- const val can only be declared at the top level of a file or inside an object declaration, whereas val can be declared anywhere within a function, class or object.
Example of const val deceleration at the top level of file
package com.example.admindashboard
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.admindashboard.databinding.ActivityMainBinding
import com.example.admindashboard.ui.AddBooks
import com.example.admindashboard.ui.ControlPanelActivity
import com.example.admindashboard.ui.NotifficationActivity
const val message = "Hello " // correct
class MainActivity : AppCompatActivity() {
const val message2 = "hello again" // incorrect
// other code
var binding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding!!.root)
}
}
Example of const val declaration inside object
package com.example.admindashboard.utils
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
object FirebaseUtils {
const val bookNodeName = "books" // const val declaration
val firebaseDatabase = FirebaseDatabase.getInstance()
var pyqRef = firebaseDatabase.getReference("pyq")
}
Thank you for reading this article. If you found this helpful and interesting, like it.
If I got something wrong, mention it in the comments. I would love to improve.
Top comments (0)