Welcome to Scala version 2.10.2 (Java HotSpot 64-Bit Server VM, Java 1.7.0_15).
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait Reduce { type X; def add(x:X) }
Run Code Online (Sandbox Code Playgroud)
我现在宣布一个类,Foo它可以从一个Reducer或chain一个填充.
class Foo[A](val a:A) {
def fill(r: Reduce { type X = A}) = {r.add(a)}
def chain[R >:A](r: Reduce { type X = R }) = { r.add(a); new Foo(r)}
}
Run Code Online (Sandbox Code Playgroud)
我现在创建一个类,它是某种数字类型的reducer Y
class AsInt[Y: Numeric] extends Reduce {
type X = Y
var i = 0
override def add(y:Y) = {i = implicitly[Numeric[Y]].toInt(y)}
}
Run Code Online (Sandbox Code Playgroud)
而且我已经完成了
// Exiting paste mode, now interpreting.
defined trait Reduce
defined class Foo
defined class AsInt
Run Code Online (Sandbox Code Playgroud)
我现在可以创建并填充以下实例Foo:
scala> val fL = new Foo(123L)
fL: Foo[Long] = Foo@12979ef0
scala> fL.fill(new AsInt)
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.现在我链了一个:
scala> fL.chain(new AsInt)
<console>:12: error: ambiguous implicit values:
both object BigIntIsIntegral in object Numeric of type scala.math.Numeric.BigIntIsIntegral.type
and object IntIsIntegral in object Numeric of type scala.math.Numeric.IntIsIntegral.type
match expected type Numeric[Y]
fL.chain(new AsInt)
^
Run Code Online (Sandbox Code Playgroud)
现在我被卡住了.typer应该寻找某种类型R >: Long,其Numeric[R]范围是隐含的.如何Numeric[Int]或Numeric[BigInt]可能适合该法案?
typer似乎没有解决它的问题:
scala> def foo[Z >: Long](implicit N: Numeric[Z]) = println(N)
foo: [Z >: Long](implicit N: Numeric[Z])Unit
scala> foo
scala.math.Numeric$LongIsIntegral$@67236f24
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
| 归档时间: |
|
| 查看次数: |
433 次 |
| 最近记录: |