有什么办法由科特林来实现懒评价.filter().MAP().forEach等?

问题描述 投票:0回答:1

在我看来,如果我有多个过滤器()调用。该集将迭代多次。我想这样的代码:

生成全行内最好的。

set.filter{a>10}.filter{a<20}.forEach{doSomething()}
for(e in set){ // Only iterate the set one time.
    if(e.a>10){
        if(e.a<20)
            doSomething()
    }
}
kotlin
1个回答
0
投票

我认为你可以使用范围运算符来做到这一点。

set.filter{ it.a in 10..20 }.forEach{ doSomething() } 

或者如果你有做任何复杂的情况,那么你就可以创建一个返回boolean值的方法。

set.filter{ isInRange(it.a, x, y) }.forEach{ doSomething() } 

// create a function
fun isInRange(value: Int, x: Int, y: Int) = value in x..y // both inclusive 
© www.soinside.com 2019 - 2024. All rights reserved.