gpt4 book ai didi

scala - 如何获取路径依赖类型的类标签

转载 作者:行者123 更新时间:2023-12-01 01:05:07 25 4
gpt4 key购买 nike

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

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]]
}

最佳答案

你必须在你知道类型的地方召唤一个类标签。

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

但是现在宏很容易编写。
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

所以
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

关于scala - 如何获取路径依赖类型的类标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19496231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com