有条件地调用没有临时变量的成员函数

编程入门 行业动态 更新时间:2024-10-27 18:28:00
本文介绍了有条件地调用没有临时变量的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个返回对象的表达式,我想仅在某个布尔条件为真时才对结果对象调用一个方法.我想在一个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)

更多推荐

有条件地调用没有临时变量的成员函数

本文发布于:2023-07-26 11:40:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1215998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   变量   函数   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!