Scala:如何定义“通用”函数参数?(Scala: How to define “generic” function parameters?)
我正在试图学习Scala,并在Haskell有一点经验。 对我而言奇怪的一件事是,Scala中的所有函数参数必须用Haskell不需要的类型注释。 为什么是这样? 尝试把它作为一个更具体的例子:一个add函数是这样写的:
def add(x:Double, y:Double) = x + y
但是,这仅适用于双精度(同样,int也因为隐式类型转换而工作)。 但是如果要定义自己的类型定义自己的+运算符,该怎么办? 你如何编写一个可以定义+运算符的任何类型的add函数?
I am trying to learn Scala now, with a little bit of experience in Haskell. One thing that stood out as odd to me is that all function parameters in Scala must be annotated with a type - something that Haskell does not require. Why is this? To try to put it as a more concrete example: an add function is written like this:
def add(x:Double, y:Double) = x + y
But, this only works for doubles(well, ints work too because of the implicit type conversion). But what if you want to define your own type that defines its own + operator. How would you write an add function which works for any type that defines a + operator?
原文:https://stackoverflow.com/questions/1252915