如果我在类中有类型别名定义,我可以在运行时将其与静态已知的类型或其他类型别名进行比较吗?考虑:
type ConsArguments = (Option[Long], String, Option[String], Iterable[Input])
trait Type {
val name :String
type Value
def apply(id :Option[Long], name :String, label :Option[String], inputs :Iterable[Input]=Iterable()) :Statistic
}
class BaseType[V :TypeTag](val name :String, constructor :((ConsArguments)) => Statistic {type Value=V}) extends Type{
type Value = V
def apply(id :Option[Long], name :String, label :Option[String], inputs :Iterable[Input]=Iterable()) :Statistic{type Value=V} =
constructor((id, name, label, SortedSet[Input]()(Input.nameOrdering)++inputs))
}
val LongValued = new BaseType[Long]("long", (LongStatistic.apply _).tupled)
val lv :Type = LongValued
println("type of LongValued: "+universe.typeOf[LongValued.Value]+" is Long? "+(universe.typeOf[LongValued.Value]=:=universe.typeOf[Long]))
println("type of lv: "+universe.typeOf[lv.Value]+" is Long? "+(universe.typeOf[lv.Value]=:=universe.typeOf[Long]))
第一个比较为true,第二个为false。我能以某种方式解决它吗?通常,我将有更多的“类型”实例充当域模型中类的构造函数,并希望遍历这些类型的集合并选择一个匹配的实例。
好的,我知道了。更改非常简单:
type ConsArguments = (Option[Long], String, Option[String], Iterable[Input])
trait Type {
val name :String
type Value
val tpe :universe.Type
def apply(id :Option[Long], name :String, label :Option[String], inputs :Iterable[Input]=Iterable()) :Statistic
}
class BaseType[V :TypeTag](val name :String, constructor :((ConsArguments)) => Statistic {type Value=V}) extends Type{
type Value = V
val tpe = typeOf[V]
def apply(id :Option[Long], name :String, label :Option[String], inputs :Iterable[Input]=Iterable()) :Statistic{type Value=V} =
constructor((id, name, label, SortedSet[Input]()(Input.nameOrdering)++inputs))
}
val LongValued = new BaseType[Long]("long", (LongStatistic.apply _).tupled)
val lv :Type = LongValued
println("type of lv: "+lv.tpe+" is Long? "+(lv.tpe=:=universe.typeOf[Long]))
尽管如此,在整个代码中都使用double(类型...和val _:Type)声明还是有点令人讨厌。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句