【问题标题】:Kotlin - How to make a for loop that iterate and return multiple valuesKotlin - 如何制作一个迭代并返回多个值的 for 循环
【发布时间】:2019-08-05 01:23:31
【问题描述】:

我创建了一个函数,它通过 if 语句在列表上进行迭代以找到匹配项,当找到匹配项时,我想返回匹配值,但它只发生一次,返回语句位于函数的末尾,并且if 语句。

问题是,如何避免此功能在第一次匹配后停止?还有其他方法吗?我没有使用的其他功能? 当我运行这段代码时,我得到了这个:

  Anything      
  Not a match      
  Not a match      

这是我的代码:

   class Class1(var self: String,var tipo: String,var element: String)       
   var test_class = Class1("","","")       

   fun giver(){       
      test_class.self = "Anything"       
       test_class.tipo = "Something"       
       test_class.element = "Nothing"       
   }       



   class Funciones(){       
           fun match_finder(texto: String): Any{       
               var lista = listOf<String>(test_class.self,test_class.tipo,test_class.element)       
               var lista_de_listas = listOf<String>("test_class.self","test_class.tipo","test_class.element")       
               var count = -1       
               var variable = ""       
               for (i in lista_de_listas){       
                   count = count + 1       
                   println(count)       
                   if (texto == i){       
                       lista_de_listas = lista       
                       var variable = lista_de_listas[count]        
                       return variable       

                   }           
               }       
              return "Not a match"       
           }        
       }           


   fun main(){       
       giver()       
       var x = "test_class.self"       
       var z = "test.class.tipo"       
       var t = "test.class.element"       
       var funcion = Funciones()       
       var y = funcion.match_finder(x)       
       var c = funcion.match_finder(z)       
       var r = funcion.match_finder(t)       
       println(y)       
       println(c)       
       println(r)       

   }

【问题讨论】:

    标签: function loops if-statement kotlin return-value


    【解决方案1】:

    您的示例中有一些拼写错误。您查询test.class.tipo,但在您的lista_de_listas 中,test_class.tipo 带有下划线。 test.class.element 也是如此。

    但您应该考虑使用 Map 而不是两个列表进行查找:

    fun match_finder(texto: String): Any{
        val map = mapOf(
            "test_class.self" to test_class.self,
            "test_class.tipo" to test_class.tipo,
            "test_class.element" to test_class.element
            )
    
        return map.getOrDefault(texto,"Not a match")
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 2013-04-24
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      相关资源
      最近更新 更多