Why does Kotlin need "const" keyword?

This topic made me think for some reason about one interesting feature of const. It should be possible to build a library version check, ensuring its version is equal or higher than the version used to compile with.

Let’s say we have a library with the following code

class Version(val v: String): Comparable ...
private const val compiledVersion = Version("1.0")
val version = libraryVersion
inline fun checkVersion() = assert(version >= compiledVersion)

At first this seems to do nothing, but if called from a different application, this will ensure at runttime that the library is of the right version. Combined with static analysis and a annotation like SinceVersion this could be quite powerful for library authors. The only problem is that checkVersion fails if it is called without inlining it.

1 Like