在斯卡拉使用TypeTag多态返回类型

问题描述 投票:1回答:1

我想要做的是使用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]

我怎样才能提前元素类型?

scala types compiler-errors type-systems
1个回答
2
投票

我不知道这是可能与这些定义。如何改变定义一下?

trait Parent[T]

implicit object IntChild extends Parent[Int]
implicit object StringChild extends Parent[String]

object SomeClass {
  def of[A: Parent]: Parent[A] = implicitly
}

这可以确保一切都在类型级别完成,让你得到你想要的返回类型。它需要在implicitIntChildStringChild修改。有没有需要有另一个名为T类型参数,因为这将永远是相同的例子A

© www.soinside.com 2019 - 2024. All rights reserved.