简体   繁体   English

kotlin 返回布尔函数

[英]kotlin return boolean function

i did some research on boolean return type function and found out it's safer to use with null-able check.我对布尔返回类型函数进行了一些研究,发现与可空检查一起使用更安全。 i have some understanding issue, compiler doesn't like what i did.我有一些理解问题,编译器不喜欢我所做的。 i also tried with if statement and it somehow returns only false.我也试过 if 语句,它以某种方式只返回 false。 can anyone please clear up my head?任何人都可以请清理我的头吗? thanks!谢谢!

    fun check(list:ArrayList<String>): Boolean {
    var test: Boolean?= null
    for (i in list) {
        when (i=="a") {
            true -> test == true
            false -> test == false
        }
    }
    return test!!
}

Since this function only returns a true or false, you shouldn't be making the variable test nullable.由于此函数仅返回 true 或 false,因此不应将变量test设为可空。 But the compiler will complain if you remove the ?但是如果删除? and the = null because it can't guarantee the code in your for loop will ever be called (because the list could be empty).并且= null因为它不能保证你的 for 循环中的代码会被调用(因为列表可能是空的)。

As for why it's giving you the wrong result, it's because you're changing the value of test for every item in the list, so the final value depends only on the last element in the list.至于为什么它给你错误的结果,那是因为你正在改变列表中每个项目的test值,所以最终值只取决于列表中的最后一个元素。 Also, if the list is empty, test will remain null and you'll get an exception when you use test!!此外,如果列表为空,则test将保持为空,并且在使用test!!时会出现异常test!! . .

I don't know if you're trying to see if any element of the list is “a” or if all elements are “a”, but for the sake of discussion I'll assume it is the first one.我不知道您是想查看列表中的任何元素是“a”还是所有元素都是“a”,但为了便于讨论,我假设它是第一个。 So the strategy here is to make false the default, and change it to true if you find any elements that are “a”.所以这里的策略是将 false 设为默认值,如果发现任何元素为“a”,则将其更改为 true。 And once you find one, there's no reason to keep checking so you can break out of the loop.一旦你找到一个,就没有理由继续检查,这样你就可以跳出循环。

var test = false // not nullable
for (i in list)
    if (i == "a") {
        test = true
        break
    }
return test

As a side note, Kotlin has a higher-order function for List that checks for any element that satisfies the lambda so the above code could be replaced with作为旁注,Kotlin 有一个 List 的高阶函数,用于检查满足 lambda 的任何元素,因此上面的代码可以替换为

return list.any { it == "a" }

Another side note: if you are setting a Boolean based on some criteria, a when statement is overkill and makes your code more complicated.另一个注意事项:如果您根据某些标准设置布尔值,则 when 语句是多余的,并且会使您的代码更加复杂。 You could have replaced your when statement with test = i == "a" and had equivalent behavior (although as you found, it wasn't right behavior to begin with).您可以用test = i == "a"替换您的 when 语句并具有等效的行为(尽管正如您发现的那样,这不是正确的行为)。

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

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