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

时间:2019-03-06 10:33:47

标签: scala functional-programming pipe-forward-operator

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

def complexComputation(input: String): String = {
  val first = input.reverse
  val second = first + first
  val third = second * 3
  third
}

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

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

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

2 个答案:

答案 0 :(得分:6)

实际上,Scala 2.13是可能的。它将介绍pipe

import scala.util.chaining._

input //"str"
 .pipe(s => s.reverse) //"rts"
 .pipe(s => s + s) //"rtsrts"
 .pipe(s => s * 3) //"rtsrtsrtsrtsrtsrts"

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

答案 1 :(得分:1)

如您所述,可以自己实现pipe,例如:

implicit class Piper[A](a: A) {
  def pipe[B](f: A => B) = {
    f(a)
  }
}

val res = 2.pipe(i => i + 1).pipe(_ + 3)
println(res)  // 6

val resStr = "Hello".pipe(s => s + " you!")
println(resStr)  // Hello you!

或者看看https://github.com/scala/scala/blob/v2.13.0-M5/src/library/scala/util/ChainingOps.scala#L44

相关问题