简体   繁体   English

kotlin中的lazy值function如何求值取值

[英]How to evaluate and take function value lazy in kotlin

What I'm trying to achieve in my personal project is an 'evaluator function', that should elect a valid strategy, without invoking that twice.我在我的个人项目中试图实现的是一个“评估函数”,它应该选择一个有效的策略,而不用调用它两次。 Currently, my code is:目前,我的代码是:

fun electStrategy() = listOf({ attemptStrategyA(x) }, { attemptStrategyB(x) })
                      .find{ it.invoke() == true } ?.invoke()

// where `attemptStrategyA(x)` and `attemptStrategyB(x)` return `T`

As you can see from the above, I need to first evaluate the strategies in a lazy fashion and then, when the predicate condition is met, I would like to get elected strategy value. As you can see from the above, I need to first evaluate the strategies in a lazy fashion and then, when the predicate condition is met, I would like to get elected strategy value.

How can I do the above without having to evaluate such strategy twice and more elegantly?我怎样才能做到以上几点而不必两次更优雅地评估这种策略?

I think your example has a problem with its predicate.我认为您的示例的谓词有问题。 But assuming predicate() is a function that returns true or false on a result of a strategy invocation, you could write it this way:但假设predicate()是一个 function,它根据策略调用的结果返回 true 或 false,您可以这样写:

fun electStrategy() = sequenceOf({ attemptStrategyA(x) }, { attemptStrategyB(x) })
    .map { it.invoke() }
    .firstOrNull { predicate(it) }

Using sequenceOf instead of listOf makes the .map operation lazy, which means the predicate will be evaluated on the result of a strategy before the next strategy is attempted.使用sequenceOf而不是listOf使.map操作变得惰性,这意味着在尝试下一个策略之前将根据策略的结果评估谓词。

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

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