有条件地调用没有临时变量的成员函数 [英] Conditionally invoke member function without a temporary var

查看:37
本文介绍了有条件地调用没有临时变量的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回对象的表达式,我想仅在某个布尔条件为真时才对结果对象调用一个方法.我想在一个val中获取结果(无论是对象,还是调用对象上的方法的结果).

I have an expression returning an object, and I want to invoke a method on the resulting object only if a certain boolean condition is true. I want to get the result (whether the object, or the result of invoking the method on the object) in a val.

一种方法是使用临时变量,例如在以下示例中,其中 List(3, 1, 2) 是(可能很复杂)返回对象的表达式,list 是临时变量,.sorted 是我想有条件地调用的方法:

One way is to use a temporary var, such as in the following example, in which List(3, 1, 2) is the (potentially complicated) expression returning an object, list is the temporary var, and .sorted is the method I want to conditionally invoke:

import scala.util.Random

val condition = Random.nextBoolean
val result = {      
  var list = List(3, 1, 2);
  if (condition) list = list.sorted
  list
}

这样做的规范方法是什么,也许使用临时变量?

What would be the canonical way to do this, perhaps without using a temporary var?

注意

if (condition) List(3, 1, 2).sorted else List(3, 1, 2)

不太令人满意,因为 List(3, 1, 2) 通常可能是一个复杂的表达式,我不想重复.

is not quite satisfactory because List(3, 1, 2) may in general be a complicated expression that I don't want to repeat.

这是我发现的一种方法,不幸的是它涉及提供显式类型(并且比上述引入临时变量更长、更复杂):

Here is one method I found that unfortunately involves giving explicit types (and is longer and more complicated than introducing a temporary var as above):

val condition = Random.nextBoolean
val result =
  (
    if (condition)
      {l: List[Int] => l.sorted}
    else
      identity(_: List[Int])
  ).apply(List(3, 1, 2))

我怀疑一定有一种我没能认出的更整洁的方式.

I suspect there must be a tidier way that I have failed to recognize.

更新:一个稍微不那么丑的方法,不幸的是仍然需要明确的类型信息:

Update: A slightly less ugly method that unfortunately still requires explicit type information:

val condition = Random.nextBoolean    
val result = {
    l: List[Int] => if (condition) l.sorted else l
  }.apply(List(3, 1, 2))

推荐答案

Scala 2.13 开始,标准库现在提供链式操作 pipe它可用于转换/管道具有感兴趣函数的值,从而避免中间变量:

Starting Scala 2.13, the standard library now provides the chaining operation pipe which can be used to convert/pipe a value with a function of interest, and thus avoids an intermediate variable:

import scala.util.chaining._

List(3, 1, 2).pipe(list => if (condition) list.sorted else list)

这篇关于有条件地调用没有临时变量的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆