/ / scala पथ-निर्भर प्रकार का क्लैस्टैग कैसे प्राप्त करें - scala

स्केल कैसे पथ-निर्भर प्रकार के क्लैसस्टैग को प्राप्त करें - स्कैला

मेरे पास एक अमूर्त पथ पर निर्भर प्रकार है जिसे मुझे 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]]
}

उत्तर:

जवाब के लिए 3 № 1

आपको एक वर्ग टैग संकलित करना होगा जहाँ आप प्रकार जानते हैं

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