方法重载中的类型擦除问题 [英] Type erasure problem in method overloading

查看:53
本文介绍了方法重载中的类型擦除问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有以下签名的重载方法-

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
     }
}

此方法面临两个问题-

  1. 如何使用Seq中的值?
  2. 如何避免不应该来这里的情况?

谢谢.

推荐答案

对于方法重载,可以使用

For method overloading you can use

  1. 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")))

    1. 磁铁

    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")))
    

    基于泛型的重载方法

    这篇关于方法重载中的类型擦除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆