对值的链接操作而无需命名中间值

Sum*_*uma 5 functional-programming scala pipe-forward-operator

有时我会执行一系列计算,逐渐转换一些值,例如:

def complexComputation(input: String): String = {
  val first = input.reverse
  val second = first + first
  val third = second * 3
  third
}
Run Code Online (Sandbox Code Playgroud)

命名变量有时很麻烦,我想避免这样做。我为此使用的一种模式是使用链接值Option.map

def complexComputation(input: String): String = {
  Option(input)
    .map(_.reverse)
    .map(s => s + s)
    .map(_ * 3)
    .get
}
Run Code Online (Sandbox Code Playgroud)

使用Option/ get但是对我来说并不自然。还有其他通常的方法吗?

Krz*_*sik 7

实际上,使用Scala 2.13是可能的。它将介绍 管道

import scala.util.chaining._

input //"str"
 .pipe(s => s.reverse) //"rts"
 .pipe(s => s + s) //"rtsrts"
 .pipe(s => s * 3) //"rtsrtsrtsrtsrtsrts"
Run Code Online (Sandbox Code Playgroud)

版本2.13.0-M1已经发布。如果您不想使用里程碑版本,也许考虑使用backport

  • @Suma结帐[源代码](https://github.com/scala/scala/blob/v2.13.0-M5/src/library/scala/util/ChainingOps.scala#L44)。简直太简单了。它只是添加到每个类的扩展方法。 (3认同)
  • @Suma如果您想从选项中提取它,则只需要一个“ get”即可。问题是,为什么要使用“ Option”开头?要处理空值? (2认同)
  • @YuvalItzchakov不。这只是不存在的`Id` monad的替代品。如果对“ Id”单子目录有适当的支持,则甚至不需要“管道”,因为它与“ Id”单子目录上的“ map”相同。 (2认同)