简体   繁体   English

使用数字泛型的Scala操作

[英]Scala operations with Numeric generics

When I tried to do 当我尝试去做

def subtract[T: Numeric](x: T, y: T) : T = x-y

in Scala 2.12, the - is not recognized. 在Scala 2.12中, -不被识别。 However, this is basically equivalent to what Addition with generic type parameter in Scala suggests. 但是,这基本上等同于Scala中具有泛型类型参数的Addition建议的内容。 What do I need to change? 我需要更改什么?

The easiest thing to do is import Numeric.Implicits._ . 最简单的方法是import Numeric.Implicits._ This adds that standard infix operators, - , * , etc., to the current implicit scope. 这会将标准的中缀运算符-*等添加到当前隐式作用域。 Then everything should work as expected. 然后一切都会按预期进行。

Alternatively, you can pull down the implicit and use it directly. 或者,您可以拉下隐式并直接使用它。

def subtract[T: Numeric](x: T, y: T) : T = implicitly[Numeric[T]].minus(x,y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM