简体   繁体   English

如何在Kotlin中的函数中返回变量

[英]How to return a variable in a function in kotlin

I created a function that recieves input and compare it to a list, when find a match it return the match, in this case this match is the attribute of a class that i created. 我创建了一个接收输入并将其与列表进行比较的函数,当找到匹配项时它返回匹配项,在这种情况下,此匹配项是我创建的类的属性。

I understand that the problem is with the return statement, so in the beginning of the function I declare the return as "Any", further more than that I'm kinda lost. 我知道问题出在return语句上,因此在函数的开头,我将return声明为“ Any”,这远不止于此。

The error is this: A 'return' expression required in a function with a block body ('{...}') 错误是这样的:具有块体('{...}')的函数中需要'return'表达式

   class Class1(var self: String)       
   var test_class = Class1("")       

   fun giver(){       
       test_class.self = "Anything"       
   }

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

                   }       


               }       

           }       
       }           


   fun main(){       
       giver()       
       var x = "test_class.self"       
       var funcion = Funciones()       
       var y = funcion.match_finder(x)       
       println(y)       

   }

I searched online, if someone has the same problem, the correct code is as follows: 我在网上搜索,如果有人遇到相同的问题,则正确的代码如下:

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

               } else {
                   return "There is no match"
                  }      


           }  
        return variable     
       }       
   }   

To explain you what the problem is, let's consider the following code: 为了说明问题所在,让我们考虑以下代码:

class MyClass {
    fun doSomething(): String {
        val numbers = listOf(1, 2, 3)
        for (number in numbers) {
            if (number % 2 == 0) {
                return "There is at least one even number in the list"
            }
        }
    }
}

If you try compiling it you'll get the same error message as in your question: A 'return' expression required in a function with a block body ('{...}') . 如果尝试对其进行编译,则会收到与您的问题相同的错误消息: A 'return' expression required in a function with a block body ('{...}') Why is that? 这是为什么?

Well, we defined a function doSomething returning a String (it could be any other type) but we're returning a result only if the list of numbers contains at least one even number. 好吧,我们定义了一个函数doSomething返回一个String(它可以是任何其他类型),但是仅当数字列表包含至少一个偶数时,我们才返回结果。 What should it return if there's no even number? 如果没有偶数,应该返回什么? The compiler doesn't know that (how could it know?), so it prompts us that message. 编译器不知道(怎么知道?),因此它提示我们该消息。 We can fix the code by returning a value or by throwing an exception: 我们可以通过返回值或引发异常来修复代码:

class MyClass {
    fun doSomething(): String {
        val numbers = listOf(1, 2, 3)
        for (number in numbers) {
            if (number % 2 == 0) {
                return "There is at least one even number in the list"
            }
        }

        // return something if the list doesn't contain any even number
        return "There is no even number in the list"
    }
}

The same logic applies to your original code: what should the function return if there is no i such that texto == i ? 相同的逻辑适用于您的原始代码:如果没有i这样的texto == i ,则函数应返回什么?

Please also note that the solution you proposed may be syntactically correct - meaning it compiles correctly - but will probably do something unexpected. 另请注意,您提出的解决方案在语法上可能是正确的-意味着它可以正确编译-但可能会执行某些意外操作。 The for loop is useless since the if/else statement will always cause the function to return during the first iteration, so the value "There is no match" could be returned even if a match actually exists later in the list. for循环是无用的,因为if/else语句将始终使函数在第一次迭代期间返回,因此即使列表中的后面确实存在"There is no match"也可能返回值"There is no match"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM