Scala:在内部类型上获取 TypeTag [英] Scala: Getting a TypeTag on an inner type

查看:56
本文介绍了Scala:在内部类型上获取 TypeTag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为内部类型获取 TypeTagClassTag 以向具有类型参数的方法提供 ClassTag.具体来说,我有

I'm trying to get a TypeTag or ClassTag for an inner type to provide a ClassTag to a method with type parameters. Specicfically, I have

trait Baz
trait Foo { type Bar <: Baz }

我想做类似的事情

import scala.reflect.runtime.universe._
import scala.reflect._
typeTag[Foo#Bar] // or maybe
classTag[Foo#Bar]

但我收到没有可用的类型标签"错误.我的最终目标是为这样的事情提供 ClassTags

but I get a 'no typetag available' error. My ultimate goal is to provide ClassTags to something like this

import scala.reflect.ClassTag
class Doer[A,B]()(implicit ctA:ClassTag[A], ctB:ClassTag[B])
object Fooer extends Doer[Foo, Foo#Bar]()(classTag[Foo], classTag[Foo#Bar])

推荐答案

通常你可以从内部类型中获取类型标签和类标签就好了.然而,Foo#Bar 是一个抽象类型.类型标签和类标签都不能从抽象类型中获取.你可以得到一个弱类型标签:

Normally you can get type tags and class tags from inner types just fine. However, Foo#Bar is an abstract type. Neither type tags nor class tags can be acquired from abstract types. You can get a weak type tag instead:

scala> weakTypeTag[Foo#Bar]
res1: reflect.runtime.universe.WeakTypeTag[Foo#Bar] = WeakTypeTag[Foo#Bar]

scala> class Doer[A, B]()(implicit wttA: WeakTypeTag[A], wttB: WeakTypeTag[B])
defined class Doer

scala> new Doer[Foo, Foo#Bar]()
res2: Doer[Foo,Foo#Bar] = Doer@1994551a

这篇关于Scala:在内部类型上获取 TypeTag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆