Home > Software engineering >  Mapping array elements using a function in Kotlin
Mapping array elements using a function in Kotlin

Time:01-26

New to Kotlin from Python. In Python, I can simply use the code below to pass each element of a List to a multiline function and return an iterator of the result.

countArr = list(map(countReps, arr))

In Kotlin, I found that I had to do the following. Am I missing something?

fun LetterCountI(str: String): String {
  val arr = str.split(" ")
  var transform:(String) -> Int = {countReps(it)}
  val countArr = arr.map(transform)
  val mxIndex:Int 
  var ans:String
  if (countArr.max()!=1){
    mxIndex = countArr.indexOf(countArr.max())
    ans = arr[mxIndex]
  } else {
    ans = "-1"
  } 
  return ans;
  
}
fun countReps(str: String): Int {
  var m = mutableMapOf<Char, Int>()
  var v:Int
  for (c in str){
    if (c in m.keys){
      v = m[c]?:0
      m.put(c,v 1)
    } else {
      m.put(c,1)
    }
  }
  return m.values.max() ?: 0
}```

CodePudding user response:

I'm having a bit of a hard time understanding your code, but one thing I can tell you is that you can replace

var transform:(String) -> Int = {countReps(it)}
val countArr = arr.map(transform)

with

val countArr = arr.map(::countReps)
  •  Tags:  
  • Related