val vs. const //Kotlin Android Dev Diary

Last updated on

Written by

on

in

,

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

Comments

Leave a Reply

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