0

我知道这是可能的:

import scala.reflect._

trait Foo[A]

def isDouble[A: ClassTag](foo: Foo[A]) = classTag[A].runtimeClass == classOf[Double]

object Foo1 extends Foo[Double]
object Foo2 extends Foo[String]
assert(isDouble(Foo1))
assert(!isDouble(Foo2))

但是,现在我想做A一个抽象类型:

import scala.reflect._

trait Foo {
  type A
}

def isDouble(foo: Foo): Boolean = ???

object Foo1 extends Foo {override type A = Double}
object Foo2 extends Foo {override type A = String}
assert(isDouble(Foo1))
assert(!isDouble(Foo2))

如何实现该isDouble功能?

4

1 回答 1

0

Scala 让您将参数引用到柯里化函数的左侧(在本例中foo):

def isDouble(foo: Foo)(implicit ev: ClassTag[foo.A]) = classTag[foo.A].runtimeClass == classOf[Double]
于 2016-01-29T22:22:08.423 回答