Named constants within function


Is declaring

final typename NAMEDCONSTANT = value

in java is equivalent to

val NAMEDCONSTANT : typename = value

or I am missing something?

Sorry, if this question is too trivial - I am really new to Kotlin and don’t have much experience in Java.


Yes, in the context of variable declaration, ‘val’ in Kotlin means the same as ‘final’ in Java, namely that the variable can only be assigned once.

Incidentally, in Kotlin you can often omit the type name where the type can be easily deduced from the type of the expession on the RHS.


While we would not normally call that constants (not in Java either) the code is equivalent. The term constant is normally for something that always has the same value (not different per invocation/instantiation). In Kotlin that means you would define the constant in the companion object.


Just to add to what @pdvrieze said, you can also declare compile time constants in Kotlin (using ‘constant val’) at top-level i.e. outside any class or object.

When declared in this way, they are somewhat similar to #define macros in the C language.


Or on the top-level