加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

具有路径依赖/嵌套类型的Scala类型擦除问题

发布时间:2020-12-14 05:01:04 所属栏目:百科 来源:网络整理
导读:我们假设如下: class Wrapper1 { case class Condition(test: String)}object Wrapper1 extends Wrapper1class Wrapper2 { case class Condition[A](test: String)}object Wrapper2 extends Wrapper2class Test type T = // whatever def test(fn: T = Wrap
我们假设如下:

class Wrapper1 {
  case class Condition(test: String)
}
object Wrapper1 extends Wrapper1

class Wrapper2 {
  case class Condition[A](test: String)
}
object Wrapper2 extends Wrapper2


class Test 
  type T = // whatever

  def test(fn: T => Wrapper1.Condition): X
  def test[R](fn: T => Wrapper2.Condition[R]): X
}

问题是由于类型擦除,这些方法在擦除后具有完全相同的类型.可以很容易地改变第二个的签名:

def test[R](fn: T => Wrapper2.Condition[R])(implicit ev: R =:= R): X

但这会混淆编译器并在其他地方使用测试方法是不可能的.出于多种设计原因,我试图保持这种方法的名称一致.有没有办法成功地做到这一点?

解决方法

似乎这不是 Scala double definition (2 methods have the same type erasure)的副本

我的建议……只需要一个方法

def test[Cond: TypeTag](fn: T => Cond): X = {
  if(typeOf[T] <:< typeOf[Wrapper1.Condition]) ...
  else if(typeOf[T] <:< typeOf[Wrapper2.Condition[_]) ...
  else ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读