本文介绍了在不命名中间值的情况下对值进行链接操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Sometimes I perform a sequence of computations gradually transforming some value, like:

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

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

Naming variables is sometimes cumbersome and I would like to avoid it. One pattern I am using for this is chaining the values using Option.map:

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

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

Using Option / get however does not feel quite natural to me. Is there some other way this is commonly done?

推荐答案

实际上,使用 Scala 2.13 .它将介绍管道:

Actually, it will be possible with Scala 2.13. It will introduce 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 已发布.如果您不想使用里程碑版本,则可以考虑使用向后移植?

Version 2.13.0-M1 is already released. If you don't want to use the milestone version, maybe consider using backport?

这篇关于在不命名中间值的情况下对值进行链接操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:21
查看更多