Since the val
variable is read-only, in most cases we could treat it as a constant. We need to be aware that its initialization may be delayed, so this means that there are scenarios where the val
variable may not be initialized at compile time, for example, when assigning the result of the method call to a value:
val fruit:String = getName()
This value will be assigned at runtime. There are, however, situations where we need to know the value at compile time. The exact value is required when we want to pass parameters to annotations. Annotations are processed by an annotation processor that runs long before the application is started:
To make absolutely sure that the value is known at compile time (and thus can be processed by an annotation processor), we need to mark it with a const
modifier. Let's define a custom annotation, MyLogger
, with a single parameter defining maximum log entries and annotate a Test
class with it:
const val MAX_LOG_ENTRIES = 100 ...