0

I am trying to validate if props:List<String> values ​​exist with message:String and return if the value is true or false.

fun main() {

val message = """
            {
                "id": "xxxxx",
                "action": "Do",
                "resource": "Login",
                "type": "ok",
                "data": {
                "username": "+521234567890",
                "password": "12345"
            }
            }"""
val words = listOf("dog","flower","cat")
messageValidator(message,words)}


fun validator(message:String, props:List<String>):Boolean{

val words = props.iterator()
val messagejson = Json.parseJson(message).jsonObject


for(x in words){
    //println(x)
    //val dataWords = messagejson.containsKey(x)
    val dataWords = messagejson.containsKey(x)
    //println(dataWords)
    if (dataWords == true){
        println(x)
        return true
    }
    if (!dataWords){
        println(x)
        return false
    }
}
return false }

I really don't know how to continue validating

Ali
  • 2,702
  • 3
  • 32
  • 54
John Snow
  • 3
  • 3

2 Answers2

0

Not sure if this is what you were looking for, But this goes over every object in words, And if the message doesn't contain x it returns false, otherwise true.

for(x in words){
    if(!messagejson.containsKey(x))
        return false

}
return true
}
barbecu
  • 684
  • 10
  • 28
0

Instead of using a loop, you could also write:

fun validator(message: String, props: List<String>) =
        props.any { message.contains(it) }
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Wow! this line of code if it is interesting, I found several examples similar to yours, as I just started with kotlin because little by little I will know how to reduce lines of code. Also thanks for the help. – John Snow Jun 17 '20 at 22:44