val vs. const //Kotlin Android Dev Diary

Let’s start off by introducing val.

To define a variable in Kotlin, you may use var or val:

varval
has a mutable value (changeable)has an immutable value (read-only)

So we use val for immutable values, so what is the const keyword and what’s its difference from val?

constval
has an immutable value (read-only)has an immutable value (read-only)
initialized at compile time onlyvalue may be assigned during runtime

Other rules for const in Kotlin:

  • must be a top-level property or placed within a companion object
  • value must be a primitive type (can never have function or any class constructor as its value)
  • no custom getter

Related Posts:

Posts that may be related to "val vs. const //Kotlin Android Dev Diary":

Catzie

An odd human being who happens to have a variety of ever-changing interests, but right now they are programming, making up silly song/rap lyrics, K-pop, drawing, creating unique dessert/drink flavors, obsessing about finding out how some things works, automation, anime, video games... Ran online dessert shops Cookies PH and Catzie's Cakery in her past life.

Leave a Reply

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