我知道这是可能的:
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
功能?
Scala 让你将参数引用到柯里函数的左侧(在本例中为 foo
):
def isDouble(foo: Foo)(implicit ev: ClassTag[foo.A]) = classTag[foo.A].runtimeClass == classOf[Double]