Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Scala中使用TypeTag实现多态返回类型_Scala_Types_Compiler Errors_Type Systems - Fatal编程技术网

在Scala中使用TypeTag实现多态返回类型

在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

我想做的是使用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]]
但是它抛出了一个编译错误。因为方法的
的返回类型在编译类型中不是固定的。有没有办法从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
相同。

实际上,它在我的示例中起作用。这对我很有帮助。谢谢@如果答案对你有帮助,你能接受吗?