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

Scala:当类型参数是成员类型时,集合的类型参数在“collect”中

发布时间:2020-12-16 18:29:39 所属栏目:安全 来源:网络整理
导读:通常,在收集与特定类型匹配的序列的所有元素时,生成的集合既具有原始集合的类型,又具有为以下类型选择的类型: trait Footrait Bartrait Baz { // Works def def1(foo: Seq[Foo]): Seq[Foo with Bar] = foo collect {case foobar: Bar = foobar}} 当输入类型
通常,在收集与特定类型匹配的序列的所有元素时,生成的集合既具有原始集合的类型,又具有为以下类型选择的类型:

trait Foo
trait Bar

trait Baz {
  // Works
  def def1(foo: Seq[Foo]): Seq[Foo with Bar] = 
    foo collect {case foobar: Bar => foobar}
}

当输入类型由有界成员类型参数化并且我想要的全部是由绑定类型(而不是成员类型)参数化的序列时,这甚至有效:

trait Baz {
  type memberType <: Foo

  // Works
  def2(foo: Seq[memberType]): Seq[Foo with Bar] =
    foo collect {case foobar: Bar => foobar}
}

但是,当我真的想要返回由成员类型参数化的序列时,这会失败:

trait Baz {
  type memberType <: Foo

  // Fails
  def def3(foo: Seq[memberType]): Seq[memberType with Bar] =
    foo collect {case foobar: Bar => foobar}
}

错误信息:

error: type mismatch;
 found   : Seq[this.Foo with this.Bar]
 required: Seq[Baz.this.memberType with this.Bar]
    foo collect {case foobar: Bar => foobar}

要恢复功能,我可以在collect调用中包含成员类型,但由于签名,每个元素必须匹配该类型,这似乎是多余的:

trait Baz {
  type memberType <: Foo

  // Works
  def def4(foo: Seq[memberType]): Seq[memberType with Bar] =
    foo collect {case foobar: memberType with Bar => foobar}
}

有没有办法定义成员类型序列,以便在收集时记住其成员类型?

解决方法

这不是答案,只是一些观察.这有效:

trait Baz[A <: Foo] {
  def def3(foo: Seq[A]): Seq[A] =
    foo collect {case foobar => foobar}
}

但这不是:

trait Baz[A <: Foo] {
  def def3(foo: Seq[A]): Seq[A] =
    foo collect {case foobar: Bar => foobar}
}

这也不是:

trait Baz[A] {
  def def3(foo: Seq[A]): Seq[A] =
    foo collect {case foobar: Bar => foobar}
}

所以它似乎是模式匹配器的效果;我不认为它与收集有任何关系.一旦你将类型添加到匹配大小写,它就会以某种方式丢失信息: – /

但是作为Kaito,我实际上也很惊讶,你的前两个案例确实有效.必须(并且似乎合理)类型推断算法在已知的稳定类型(Foo)和类型参数或类型成员之间产生差异.您可能需要在scala语言邮件列表上询问一些编译器专家来回答这个问题……

(编辑:李大同)

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

    推荐文章
      热点阅读