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

数组 – Scala类型推断:不能从Array [T]推断出IndexedSeq [T]

发布时间:2020-12-16 18:50:36 所属栏目:安全 来源:网络整理
导读:在 Scala 2.11.2中,以下最小示例仅在Array [String]上使用类型ascription时进行编译: object Foo { def fromList(list: List[String]): Foo = new Foo(list.toArray : Array[String]) }class Foo(source: IndexedSeq[String]) 如果我删除了fromList中的类型
在 Scala 2.11.2中,以下最小示例仅在Array [String]上使用类型ascription时进行编译:

object Foo {    

  def fromList(list: List[String]): Foo = new Foo(list.toArray : Array[String])   

}

class Foo(source: IndexedSeq[String])

如果我删除了fromList中的类型归属,它将无法编译,并出现以下错误:

Error:(48,56) polymorphic expression cannot be instantiated to expected type;
 found   : [B >: String]Array[B]
 required: IndexedSeq[String]
  def fromList(list: List[String]): Foo = new Foo(list.toArray)
                                                       ^

为什么编译器不能在这里推断出Array [String]?或者这个问题是否与从Array到IndexedSeq的隐式转换有关呢?

解决方法

问题是.toArray方法返回某个类型B的数组,它是List [T]中T的超类.这允许您在List [Bar]上使用list.toArray,如果Bar扩展Foo,则需要Array [Foo].

是的,这个开箱即用的真正原因是编译器试图找出使用哪个B以及如何到达IndexedSeq.它似乎正在尝试解决IndexedSeq [String]要求,但B只能保证是String或String的超类;因此错误.

这是我的首选工作:

def fromList(list: List[String]): Foo = new Foo(list.toArray[String])

(编辑:李大同)

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

    推荐文章
      热点阅读