How to replace sumBy with sumOf in kotlin 1.5

Viewed 505

I have the following code:

val sum = list.itens.sumBy { item ->
    when (item.intValueI == item.intValueII) {
        true -> 1
        else -> 0
    }
}

Updating to Kotlin 1.5, I got the deprecated warning; How should I proceed to achieve the same functionality?

I tried below:

val result = list.itens.sumOf<ListItemClass> { item ->
    val intValueI = item.value ?: 0
    val intValueII = item.valueII ?: 0
    when(item.intValueI == item.IntValueII){
        true -> 1
        else -> 0
    }
}
1 Answers

Why not filter your items and count them instead of involving maths, since that seems like what you're after?

val sum = list.items.filter { it.intValue1 == it.intValue2 }.size

Or, even more simply (thanks Tenfour04 in comments!):

val sum = list.items.count { it.intValue1 == it.intValue2 }

If it's absolutely essential for some reason to use sumOf, a slightly hacky solution would be:

val sum = list.items.sumOf { 
  if (it.intValue2 == it.intValue2) 1 else 0 as Int
}

Looks like the compiler / Android Studio gets a bit confused when returning 1 & 0, hence needing an else of either it.intValue1 * 0 or 0 as Int. The former is messier, but the latter leaves a AS warning.

Related