I’m creating a validation handler function. I want...
# getting-started
d
I’m creating a validation handler function. I want it to return
Copy code
{
  "description": [
    "The field Description must be no more than 25 characters long",
    "The field Description must be at least 6 characters long"
  ],
  "title": [
    "The field Title must be between 6 and 25 characters long"
  ]
}
This is my code :
Copy code
val errorMap: MutableMap<String, ArrayList<String>> = HashMap()
        val stringArray: ArrayList<String> = ArrayList()
        e.bindingResult.fieldErrors.forEach(Consumer { error: FieldError ->
            error.defaultMessage?.let { stringArray.add(it) }
            errorMap[error.field] = stringArray
        })
But it returns:
Copy code
{
  "description": [
    "The field Title must be between 6 and 25 characters long",
    "The field Description must be no more than 25 characters long",
    "The field Description must be at least 6 characters long"
  ],
  "title": [
    "The field Title must be between 6 and 25 characters long",
    "The field Description must be no more than 25 characters long",
    "The field Description must be at least 6 characters long"
  ]
}
What’s the most elegant to to that with Kotlin ?
s
You want to create a separate ArrayList for each map key instead of using a single
stringArray
. I like to do it in
defaultValue
of
getOrPut
method:
Copy code
val message = error.defaultMessage
if (message != null) {
    errorMap.getOrPut(error.field, defaultValue = { ArrayList() }).add(message)
}
👍 1
2
j
Also, prefer `mutableMapOf`/`mutableListOf` if you don't have a particular need for a specific list or map implementation
d
Even better prefer builders instead of mutable collections:
Copy code
buildMap<String, ArrayList<String>> {
  e.bindingResult.fieldErrors.forEach { error ->
    val message = error.defaultMessage
    if (message != null) {
      errorMap.getOrPut(error.field, defaultValue = { ArrayList() }).add(message)
    }
  }
}
And perhaps consider using (mutable) lists instead of arrays.
j
@David Kubecka there are no arrays, the
stringArray
is already a list in the original code despite its name. `ArrayList`s are lists
d
Oh, sorry 🙂 Then your comment applies (the
mutableListOf
part)
👍 1
d
Thanks for the support guys !!! 🙂