Idioms for Regex Matching in When Expression

suggest change

Using immutable locals:

Uses less horizontal space but more vertical space than the “anonymous temporaries” template. Preferable over the “anonymous temporaries” template if the when expression is in a loop–in that case, regex definitions should be placed outside the loop.

import kotlin.text.regex

var string = /* some string */

val regex1 = Regex( /* pattern */ )
val regex2 = Regex( /* pattern */ )
/* etc */

when {
    regex1.matches(string) -> /* do stuff */
    regex2.matches(string) -> /* do stuff */
    /* etc */
}

Using anonymous temporaries:

Uses less vertical space but more horizontal space than the “immutable locals” template. Should not be used if then when expression is in a loop.

import kotlin.text.regex

var string = /* some string */

when {  
    Regex( /* pattern */ ).matches(string) -> /* do stuff */
    Regex( /* pattern */ ).matches(string) -> /* do stuff */
    /* etc */
}

Using the visitor pattern:

Has the benefit of closely emulating the “argument-ful” when syntax. This is beneficial because it more clearly indicates the argument of the when expression, and also precludes certain programmer mistakes that could arise from having to repeat the when argument in every whenEntry. Either the “immutable locals” or the “anonymous temporaries” template may be used with this implementation the visitor pattern.

import kotlin.text.regex

var string = /* some string */

when (RegexWhenArgument(string)) {
    Regex( /* pattern */ ) -> /* do stuff */
    Regex( /* pattern */ ) -> /* do stuff */
    /* etc */
}

And the minimal definition of the wrapper class for the when expression argument:

class RegexWhenArgument (val whenArgument: CharSequence) {
    operator fun equals(whenEntry: Regex) = whenEntry.matches(whenArgument)
    override operator fun equals(whenEntry: Any?) = (whenArgument == whenEntry)
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents