[英]Polymorphic return type by using TypeTag in Scala
我想做的是通過使用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
}
這樣可以確保所有操作都在類型級別完成,以便獲得所需的返回類型。 它需要IntChild
和StringChild
的implicit
修飾符。 不需要另一個名為T
類型參數,因為它在您的示例中始終與A
相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.