And the newbie asks, "Why `const val` instead of just `const`?"


#1

Sorry if it’s been asked before, but this is the first (admittedly nit-picky) “Huh?” question that jumped out at me as I’ve been perusing the Kotlin reference. It seems to me that the val keyword in the const val declaration is completely superfluous, since a compile-time constant is by definition just that much more immutable.

Can someone clarify the rationale behind this salty bit of syntax? Thanks.


#2

In const val, const is a soft keyword, meaning that it has special meaning only in that context, and can be used as an identifier in other contexts. If we supported const without val, we’d need to recognize const as a regular keyword. In general, we want to avoid adding unnecessary keywords to the language, and in this case we considered const val to be a good compromise.


#3

I thought at first the same, "Why not just const"… And then after a while it came to me , why not just lateinit, or for functions why not just tailrec and so on. It just makes more sense writing val after const.