what is the difference between const and val

const is used for compile-time constants, while val is used for runtime constants.

  • const must be a top-level or member-level val that is initialized with a value of type string or a primitive type.
  • val is a regular read-only property that is initialized either with the value itself or with the result of a constructor.

const: - Must be initialized with a value that is known at compile time. - The value is replaced directly in the usage place during compilation. - Can't be used with a non-primitive type or a value that's not known at compile time. - Are properties of a class, companion object, or top-level declarations.

val: - Initialized once when the code block is executed. - Cannot be reassigned after initialization. - Can be assigned with values that are determined during runtime.

Example of const:

const val PI = 3.14159
const val MAX_VALUE = 100

Example of val:

val name = "John Doe"
val age: Int = 30