https://kotlinlang.org logo
#ktor
Title
# ktor
d

dany giguere

02/20/2022, 5:55 PM
I’m learning Ktor and Kotlin. I’m trying to create a validation function for my Ktor 2 server app. I came up with :
Copy code
fun validate(title: String): Json {
        val errors: Json
        val titleArray: Array<String?>
        if(title.length < 20) {
            titleArray.add("The title must contain at least 20 characters")
        }
        if(title.length > 100) {
            titleArray.add("The title must contain no more than 100 characters")
        }
        if(titleArray.length > 0) {
            errors.title = titleArray
        }
        return Json {
            "errors": errors
        }
    }
as it is, I get this error :
Variable 'titleArray' must be initialized
s

Sam

02/20/2022, 6:23 PM
The error is telling you what you need to do. You have to initialise a variable (by assigning a value to it with
=
) before you can access it. In this case I think you'll find it easier to use a list than an array, so try:
Copy code
val titleArray = mutableListOf<String>()
👍 1
d

dany giguere

02/20/2022, 8:10 PM
thanks @Sam
2 Views