本文介绍了方法重载中的类型擦除问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个具有以下签名的重载方法-
I have two overloaded method having following signatures -
def fun(x: Seq[String]): Future[Seq[Int]] = ???
def fun(x: Seq[(String, String)]): Future[Seq[Int]] = ???
由于类型擦除,这些方法不能重载,因此会显示编译错误.我尝试使用类型标签作为解决方法-
Due to type erasure, these methods can't be overloaded and hence showing compilation error. I tried using typetags as a workaround -
def fun[t: TypeTag](values: Seq[T]): Future[Seq[Int]] = {
typeOf[T] match {
case t if t =:= typeOf[String] => ???
case t if t =:= typeOf[(String, String)] => ???
case _ => ??? // Should not come here
}
}
此方法面临两个问题-
- 如何使用Seq中的值?
- 如何避免
不应该来这里
的情况?
谢谢.
推荐答案
对于方法重载,可以使用
For method overloading you can use
-
DummyImplicit
(请参阅 @MarioGalic 的答案)
def fun(x: Seq[String]): Future[Seq[Int]] = ???
def fun(x: Seq[(String, String)])(implicit ev: DummyImplicit): Future[Seq[Int]] = ???
fun(Seq("a", "b"))
fun(Seq(("a", "b"), ("c", "d")))
trait FunTypeclass[A] {
def fun(x: A): Future[Seq[Int]]
}
object FunTypeclass {
implicit val string: FunTypeclass[Seq[String]] = x => ???
implicit val stringTuple2: FunTypeclass[Seq[(String, String)]] = x => ???
}
def fun[A](x: A)(implicit ftc: FunTypeclass[A]): Future[Seq[Int]] = ftc.fun(x)
fun(Seq("a", "b"))
fun(Seq(("a", "b"), ("c", "d")))
或
import scala.language.implicitConversions
trait FunMagnet {
def fun(): Future[Seq[Int]]
}
object FunMagnet {
implicit def fromString(x: Seq[String]): FunMagnet = () => ???
implicit def fromStringTuple2(x: Seq[(String, String)]): FunMagnet = () => ???
}
def fun(x: FunMagnet): Future[Seq[Int]] = x.fun()
fun(Seq("a", "b"))
fun(Seq(("a", "b"), ("c", "d")))
这篇关于方法重载中的类型擦除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!