Published on

Getting Creative with Kotlin Extension Functions

Authors

Today I had to write a piece of code that took multiple lists of validation errors and output a different message per none-empty list. These messages then had to be combined into one message. If there were no validation errors then no error should be displayed for that validation.

The obvious way to do this would be something like:

var combinedError = ""

if(errorList1.isNotEmpty()){
    combinedError += message1
}

if(errorList2.isNotEmpty()){
   combinedError += message2
}

...
// and a bunch of other error checks

There are a number of issues with this approach:

  1. It gets messy very fast with if statements everywhere
  2. We are forced to make combinedErrorMessage mutable
  3. ‎This is a real eyesore and hard to maintain

I thought it would be awesome if these checks could be chained together somehow to build the combined error message. I achieved this by creating a String extension function as below:

fun String.appendIfHasErrors(validationErrors: List<String>, messageIfError : String) : String {
    if(validationErrors.isNotEmpty()){
return this + messageIfError
    }
return this
}

And finally we change the first piece of code using our Kotlin extension function:

val combinedError = ""
    .appendIfHasErrors(errorList1, message1)
.appendIfHasErrors(errorList2, message2)
....

As you can see this is significantly cleaner and resolves the issues with the first approach.