I would like to write a function in Kotlin which takes a String array and sums up the length of all items in the array. I thought about something like this:
fun sumItems(values: Array<String?>): Int {
var sum: Int = 0
values.forEach { if(it != null) sum += it.length }
return sum
}
This works great but unfortunately I can not call this method for Array<String> because I get a type mismatch error then. I also can not create a function sumItems(values: Array<String>): Int because it has the same JVM signature. I could cast my argument to Array<String?> but this is unsafe.
So is there any better way to do this in Kotlin?
fun sumItems(values: Array<String>) : Intalready enough? If not, then just useArray<out String?>as parameter type. Yoni Gibbs answer already shows this and also how that method can even be more simplified...sumItems(values: Array<String>)and when I need to pass anArray<String?>I would filter it withfilterNotNull.filterNotNullis that you're creating a second collection in memory. And you're having to do the loop twice. In most cases this is probably negligible, but if working with a lot of data it's not the most efficient way.