首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得路径依赖类型的类类型

如何获得路径依赖类型的类类型
EN

Stack Overflow用户
提问于 2013-10-21 13:42:47
回答 1查看 663关注 0票数 5

我有一个抽象路径依赖类型,我需要ClassTag。有比手动提取每个具体派生类的隐式更好的方法吗?

代码语言:javascript
复制
trait Foo {
  type A // : ClassTag // Need the ClassTag of A later
  val ctA: ClassTag[A] // But can't put a context-bound on the type
}

class IntFoo extends Foo {
  type A = Int
  val ctA = implicitly[ClassTag[Int]]
}

class StringFoo extends Foo {
  type A = String
  val ctA = implicitly[ClassTag[String]]
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-21 19:06:20

您必须在知道类型的地方生成一个类标记。

代码语言:javascript
复制
scala> :pa
// Entering paste mode (ctrl-D to finish)

trait Foo {
type A
def ct[B: ClassTag] = implicitly[ClassTag[B]]
}

// Exiting paste mode, now interpreting.

defined trait Foo

scala> :pa
// Entering paste mode (ctrl-D to finish)

class IntFoo extends Foo {
type A = Int
def myct = ct[A]
}

// Exiting paste mode, now interpreting.

defined class IntFoo

scala> new IntFoo().myct
res2: scala.reflect.ClassTag[Int] = Int

但是现在宏很容易编写。

代码语言:javascript
复制
scala> :pa
// Entering paste mode (ctrl-D to finish)

object M {
def ct[A: c.WeakTypeTag](c: Context): c.Expr[ClassTag[A]] = {
import c.universe._
val a = c.prefix.tree.tpe.member(TypeName("A")).typeSignature
c.Expr(q"implicitly[ClassTag[$a]]").asInstanceOf[c.Expr[ClassTag[A]]]
}}

// Exiting paste mode, now interpreting.

scala> class Foo { type A = Int ; def f: ClassTag[A] = macro M.ct[A] }
defined class Foo

scala> new Foo().f
res15: scala.reflect.ClassTag[Int] = Int

scala> class Bar { type A = Char ; def f: ClassTag[A] = macro M.ct[A] }
defined class Bar

scala> new Bar().f
res16: scala.reflect.ClassTag[Char] = Char

所以

代码语言:javascript
复制
scala> trait Foo { type A ; def ct = macro M.ct[A] }
defined trait Foo

scala> class Bar extends Foo { type A = Int ; def p = println(ct) }
defined class Bar

scala> new Bar().p
Int
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19496231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档