Named constants within function


#1

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.


#2

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.


#3

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.


#4

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.


#5

Or on the top-level