反思类型成员?
Reflection on type members?
我知道这是可能的:
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]
我知道这是可能的:
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]