怎么了?
import Numeric.Implicits._
def myAdd[T: Numeric](x: T, y: T) = x + y // Works
myAdd(1,2)
def myInc[T: Numeric](x: T) = x + 1 // Fails at x: could not find implicit value for parameter num: scala.math.Numeric[Any]
myInc(9)
Run Code Online (Sandbox Code Playgroud)
斯卡拉2.10
与x + 1 - > Numeric + Int有关吗?
细算所以http://www.scala-lang.org/api/current/#scala.math.Numeric,看到one和fromInt我拨弄在REPL了一下,想出了:
scala> def myInc[T: Numeric](x: T) = x + implicitly[Numeric[T]].fromInt(1)
myInc: [T](x: T)(implicit evidence$1: Numeric[T])T
scala> myInc(9)
res1: Int = 10
scala> def myInc[T: Numeric](x: T) = x + implicitly[Numeric[T]].one
myInc: [T](x: T)(implicit evidence$1: Numeric[T])T
scala> myInc(9)
res2: Int = 10
Run Code Online (Sandbox Code Playgroud)
它与使用一个参数的方法无关,而是与编译器推断T类型相关Any.
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |