我想要做的是使用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
case String => StringChild
}
}
}
SomeClass.of[Array[Int]]
但它抛出一个编译错误。因为of
方法返回的类型是不固定在编译类型。有没有办法从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
}
这可以确保一切都在类型级别完成,让你得到你想要的返回类型。它需要在implicit
和IntChild
的StringChild
修改。有没有需要有另一个名为T
类型参数,因为这将永远是相同的例子A
。