Compile-Time Constants

There are special cases where a val can return different values (more on that later). When we are sure that a piece of data won’t be changed, we should use a compile-time constant.

  • It should be defined outside of any function because its value must be assigned at compile time (before the program is executed)
  • Must be one of the following basic types, because the use of more complex types for a constant could jeopardize the compile-time guarantee. | | | |---|---| | String | Short | | Int | Byte | | Double | Char | | Float | Boolean | | Long | |

💡 A const declaration gives the compiler the flexibility to perform optimization behind the scenes.

const val THE_ANSWER = 42
fun main(){
println(theAnswer)
}