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.

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. Do not use it if the when expression is in a loop.

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 of the visitor pattern.

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) {
    // when compares branches with ==, which calls equals(Any?). Kotlin does not allow a second equals overload.
    override fun equals(other: Any?) = (other as? Regex)?.matches(whenArgument) == true
    override fun hashCode() = whenArgument.hashCode()
}

Feedback about page:

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



Table Of Contents