listkotlinkotlin-when

How can i update 2 lists variables in when expression of kotlin?


fun compareWithIntermediate(output: SHR, input: Intpos): CompareResult{
 val matched = mutableListOf<String>()
 val mismatched = mutableListOf<String>()
 val modifiableAttr = mutableListOf<String>()

 compareValue(output.a.b.c, input.a.b.c,matched,mismatched)
 ......
 compareValue(output.x.y.z, input.x.y.z,matched,mismatched)

 return CompareResult(matched,mismatched)       

}


private fun compareValue(outputVal: String, inVal: String, matched:MutableList<String>, 
   mismatched:MutableList<Diff>){

   when(outputVal.compareTo(inVal)==0){
      true -> matched.add("abc")
       false -> mismatched.add(Diff("abc",outputVal,inVal))
   }
 }

So every time compareValue() is invoked i want to add values to matched or mismatched list based on condition.

How can i achieve this as multiple true/false could be possible in when. How can i add values to respective list based on condition. Does enum help solve this rather writing multiple same conditions in "when"??


Solution

  • Please use simpler if statement for your case:

    if (outputVal.compareTo(inVal) == 0) {
       matched.add("abc")
       // update mismatched list here if need
    } else {
       mismatched.add(Diff("abc",outputVal,inVal))
       // update matched list here if need
    }