Scala:如何创建一个允许我在调用时使用点表示法的函数? [英] Scala: How can I create a function that allows me to use dot notation when calling it?
问题描述
尽管阅读了Scala 风格,但我对此已经困惑了一段时间指南 - 多次调用方法.
我希望能够调用这个方法
I want to be able to call this method
def foldRVL[A,B](l: List[A], z: B)(f: (A, B) => B) = //"Right-Via-Left"
l.reverse.foldLeft(z)((a, b) => f(b, a))
使用这样的点符号List(1,2,3).foldRVL(0)(_ + _)
.
而不是这样:foldRVL(List(1,2,3), 0)(_ + _)
.
此外,有时我看到的代码显示的方法实际上要么在其签名中采用零个参数,要么比我预期的参数少一个,并且仍然使用点符号正确地采用参数.这是如何运作的?我问这个是因为这些方法使用点表示法,所以也许如果我写了这样的东西,我可以解决我的问题.
Also, sometimes I've seen code that shows methods that actually either takes zero parameters in their signature, or one fewer parameters than I would expect them to take, and still properly take a parameter using dot-notation. How does this work? I ask this because those methods work with dot-notation, so maybe if I wrote something like that I could solve my problem.
推荐答案
对于问题的第一部分,您可能需要查看 隐式类:
For the first part of your question, you probably need to look at implicit classes:
implicit class RichRVLList[A](l:List[A]) {
def foldRVL[B](z: B)(f: (A, B) => B) = //"Right-Via-Left"
l.reverse.foldLeft(z)((a, b) => f(b, a))
}
List(1,2,3).foldRVL(1)(_ + _) // output: res0: Int = 7
您可以使用隐式包装器丰富"现有类来添加"新方法.
You can "enrich" existent class using implicit wrapper to "add" new methods.
至于第二部分,您可能想要隐式参数.隐式参数是按类型从当前作用域推导出来的.下面的示例中使用了一些预定义的隐式值,例如 Numerics
:
As for the second part, probably you want implicit parameters. Implicit parameters are deduced from the current scope by type. There are some predefined implicit values, such as Numerics
, that were used in the example below:
def product[T](els:TraversableOnce[T])(implicit num:Numeric[T]) = {
els.fold(num.one)((x1, x2) => num.times(x1, x2))
}
product(List(1, 2, 3)) // res1: Int = 6
product(List(1, 2.5, 3)) //res2: Double = 7.5
这篇关于Scala:如何创建一个允许我在调用时使用点表示法的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!