https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dany giguere

03/10/2023, 1:20 AM
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

Svyatoslav Kuzmich [JB]

03/10/2023, 6:39 AM
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

Joffrey

03/10/2023, 8:28 AM
Also, prefer `mutableMapOf`/`mutableListOf` if you don't have a particular need for a specific list or map implementation
d

David Kubecka

03/10/2023, 10:01 AM
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

Joffrey

03/10/2023, 12:44 PM
@David Kubecka there are no arrays, the
stringArray
is already a list in the original code despite its name. `ArrayList`s are lists
d

David Kubecka

03/10/2023, 12:45 PM
Oh, sorry 🙂 Then your comment applies (the
mutableListOf
part)
👍 1
d

dany giguere

03/10/2023, 2:33 PM
Thanks for the support guys !!! 🙂
7 Views