我有两个特征,它们的实例对象定义如下:
package reflection
trait Monoid[T] {
def id: T
def op(lhs: T, rhs: T): T
}
trait ADTHelper[T]{
type V
def create(value: V): T
def get(adt: T): Any
}
case class Avg(avg: Double, n: Int)
object AvgMonoid extends Monoid[Avg] with ADTHelper[Avg]{
override def id: Avg = Avg(0, 0)
override def op(lhs: Avg, rhs: Avg): Avg =
Avg( (lhs.avg * lhs.n + rhs.avg * rhs.n)/(lhs.n + rhs.n), lhs.n + rhs.n)
override type V = Double
override def create(value: Double): Avg = Avg(value, 1)
override def get(adt: Avg): Any = adt.avg
}
object MinMonoid extends Monoid[Double] with ADTHelper[Double]{
override def id: Double = Double.MaxValue
override def op(lhs: Double, rhs: Double): Double = if(lhs < rhs) lhs else rhs
override type V = Double
override def create(value: Double): Double = value
override def get(adt: Double): Any = adt
}
我希望在运行时从名称中获取monoid实例。例如,如果我说"min"
,我想要MinMonoid
个对象,"avg"
应该给AvgMonoid
个对象,等等。所以我有以下设置:
object Test extends App {
val AGGREGATORS_NAME_DICT = Map(
"avg" -> "reflection.AvgMonoid",
"min" -> "reflection.MinMonoid",
"max" -> "reflection.MaxMonoid"
)
val AGGREGATORS_ADT_DICT = Map(
"avg" -> "reflection.Avg",
"min" -> "scala.Double",
"max" -> "scala.Double"
)
val mirror = runtimeMirror(getClass.getClassLoader)
def stringToTypeTag[A](name: String): TypeTag[A] = {
val tpe = mirror.staticClass(name).selfType
TypeTag(mirror, new api.TypeCreator {
def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
if (m eq mirror) tpe.asInstanceOf[U#Type]
else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
})
}
def resolve[T](fname: String): Option[Monoid[T] with ADTHelper[T]] = for {
monoidName <- AGGREGATORS_NAME_DICT.get(fname)
adtName <- AGGREGATORS_ADT_DICT.get(fname)
tag <- Option{stringToTypeTag[T](adtName)}
instance <- Option {
mirror
.reflectModule(mirror.staticModule(monoidName))
.instance
.asInstanceOf[Monoid[T] with ADTHelper[T]]
}
} yield instance
}
现在的问题是: 我能做到:
println(resolve("min").get.op(1.0, 2.0))
但我不能这样做:
val monoid = resolve("min").get
println(monoid.op(1.0, 2.0))
因为稍后monoid
的类型为Monoid[Nothing] with ADTHelper[Nothing]
。我无法使用我提出的T
方法解析trait Monoid[T]
和trait ADTHelper[T]
的基础类型resolve
。如何修改resolve
函数,以便使用基础类型T
解析特征?
我知道如果我使用resolve[Double](...)
进行呼叫,它会起作用,但我希望这可以在运行时从AGGREGATORS_ADT_DICT
解决。
答案 0 :(得分:2)
在运行时解析T
是不可能的,因为那时 没有T
来解决!当您编写resolve("min")
时,编译器具有以在编译期间确定其类型参数。并且由于这些论点并未告诉T
任何内容,并且上下文没有提供预期类型(例如val monoid: Monoid[Double] = resolve("min")
),它将推断{{1}请注意Nothing
的代码在这里根本不重要,只有它的类型签名。
您可以使resolve
成为宏,从而在宏的运行时确定resolve
,即使用此宏的程序的编译时间。但这只适用于您在编译时知道名称的情况(例如,它是一个文字字符串)。