在Scala中使用TypeTag实现多态返回类型
我想做的是使用TypeTag在Scala函数中返回泛型类型。下面是示例代码在Scala中使用TypeTag实现多态返回类型,scala,types,compiler-errors,type-systems,Scala,Types,Compiler Errors,Type Systems,我想做的是使用TypeTag在Scala函数中返回泛型类型。下面是示例代码 trait Parent[T] object IntChild extends Parent[Int] object StringChild extends Parent[String] object SomeClass { def of[A: TypeTag]: Parent[T] = { getElementType[A] match { case Int => IntChild
trait Parent[T]
object IntChild extends Parent[Int]
object StringChild extends Parent[String]
object SomeClass {
def of[A: TypeTag]: Parent[T] = {
getElementType[A] match {
case Int => IntChild
case String => StringChild
}
}
}
SomeClass.of[Array[Int]]
但是它抛出了一个编译错误。因为方法的的返回类型在编译类型中不是固定的。有没有办法从TypeTag获取类型信息并将类型嵌入返回的类型中
我所期待的是
// T is inferred from TypeTag A.
def of[A: TypeTag, T]: Parent[T] = {
//...
}
我发现这段代码还没有通过编译。因此,我们需要修复从A的TypeTag推断出的类型信息
def of[A: TypeTag]: Parent[_] = {
//...
}
这就是错误所在
type mismatch;
[error] found : Array[Int]
[error] required: Array[_$1]
如何提前获取元素类型?我不确定这些定义是否可行。稍微修改一下定义怎么样
trait Parent[T]
implicit object IntChild extends Parent[Int]
implicit object StringChild extends Parent[String]
object SomeClass {
def of[A: Parent]: Parent[A] = implicitly
}
这样可以确保在类型级别完成所有操作,从而获得所需的返回类型。它需要IntChild
和StringChild
上的implicit
修饰符。不需要另一个名为T
的类型参数,因为它在您的示例中始终与A
相同。实际上,它在我的示例中起作用。这对我很有帮助。谢谢@如果答案对你有帮助,你能接受吗?