有时我执行一系列计算逐渐转换某些值,如:
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对我来说并不自然.还有其他一些常见方法吗?
解决方法
实际上,它可以用
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"