Imagine a simple function that split a string:
fun checkedSplit(s: String): List<String>? {
return if (Regex("$[A-Z/]*^").matches(s)) s.split(Regex("/")) else null
}
This function is worst for performance reasons (compile a Regex is costly). A best implementation is:
fun checkedSplit(s: String): List<String>? {
return if (regexCheck.matches(s)) s.split(regexSplit) else null
}
private val regexCheck = Regex("$[A-Z/]*^")
private val regexSplit = Regex("/")
But this is painful for a developer to extract all these Regex.
In my use cases, it’s not simple Regex, but custom complex patterns like CSS selectors and XPath expressions used in DSL-style Kotlin code and there are plenty of them.
Extract all of them make the DSL code unreadable. Imagine an xsl or a css file with all the xpath or selectors far from its use…
I may have missed a feature in Kotlin, if not I suggest setting a new keyword like “final” or whatever:
fun checkedSplit(s: String): List<String>? {
return if (final(Regex(".*")).matches(s)) s.split(final Regex ("/")) else null
}
Under the wood, Kotlin replace the final expression by a static final field (for java) with a mangled name.
At compilation time, Kotlin must check the absence of any contextual variable (closures…) in the final expression.