使用点表示法在 Scala 中链接函数 [英] Chaining function in Scala using dot notation
问题描述
到目前为止,我所知道的在 Scala 中将函数链接在一起的唯一本机方法是使用 andThen/compose.它完成了工作,但看起来仍然很笨重.例如,如果我有 3 个函数应用于一个值( f1(f2(f3(value))) ),我必须做这样的事情:
So far, the only native method of chaining functions together in Scala I know of is using andThen/compose. It gets the job done but still looks very clunky. For example, if I have 3 functions to apply to a value ( f1(f2(f3(value))) ), I have to do something like that:
(f1 _ andThen f2 andThen f3)(value)
当链更长并且函数需要超过 1 个参数时,问题会变得更糟.F# 使用|>"运算符非常优雅地解决了这个难题,但这种方法在 Scala 中效果不佳,因为该语言在很大程度上依赖于点表示法,而柯里化是可选的.
Problems get even worse when the chain is longer and the functions require more than 1 parameter. F# solves this conundrum very elegantly with the '|>' operator, but that approach doesn't work well in Scala, since the language relies a lot on dot notation and currying is optional.
所以问题是,是否可以在 Scala 中做这样的事情:
So the question is, is it possible to do something like this in Scala:
def addNumber(i: Int, s: String) = s + i
def doubleString(s: String) = (s + s, (s + s).length)
def trimString(i: (String, Int)) = i._1.substring(0, i._2-1)
addNumber(1,"Hello").doubleString.trimString
换句话说,我们可以使用点符号链接函数,前提是它们具有不同的返回类型/参数.
In other words can we chain functions using dot-notation, provided that they have different return types/arguments.
推荐答案
从 Scala 2.13
开始,您可以使用 pipe
链接操作员:
Starting Scala 2.13
you can use the pipe
chaining operator:
import scala.util.chaining._
// def addNumber(i: Int, s: String) = s + i
// def doubleString(s: String) = (s + s, (s + s).length)
// def trimString(i: (String, Int)) = i._1.substring(0, i._2-1)
"Hello".pipe(addNumber(1, _)).pipe(doubleString).pipe(trimString)
// "Hello1Hello"
这篇关于使用点表示法在 Scala 中链接函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!