首页 > 解决方案 > Referring to "it" in the outer for loop

问题描述

I have a question about accessing the it in the outer loop in kotlin. I am trying to see how many letters differ between two strings. I would like to know is there a way to access the outer for loop with it?

fun compute (stringOne: String, stringTwo: String): Int {
  var i = 0
  stringOne.toCharArray().forEach @loop{
    stringTwo.toCharArray().forEach {
      if (it@loop.equals(it))
        i++
    }
   }
  return i
}

标签: loopskotlinlabel

解决方案


您可以将命名参数用于循环

fun compute (stringOne: String, stringTwo: String): Int {
  var i = 0
  stringOne.toCharArray().forEach { char1 ->
    stringTwo.toCharArray().forEach { char2 ->
      if (char1 == char2)
        i++
    }
   }
  return i
}

推荐阅读