Warm tip: This article is reproduced from serverfault.com, please click

scala-inumtable.List [Object]找到所需的List [Contact]

(scala - inumtable.List[Object] found required List[Contact])

发布于 2020-11-28 15:34:41

我在以下代码中遇到了一些问题:

object GestorContactos {
  private var listaContantocs:List[Contacto] = Nil
  def insertarOrd(c:Contacto):List[Contacto]=listaContantocs={
    var aux:List[Contacto]=listaContantocs.sortBy(_.edad)
    aux.filter(x=>x.edad<c.edad)::c::(aux.filter(x=>x.edad>c.edad))
  }

aux.filter(x=>x.edad<c.edad)返回List [Contacto],并且相同aux.filter(x=>x.edad>c.edad)

问题是,当我尝试将两个Contacto对象的结果(var c)添加到一个列表中时,出现以下错误:

type mismatch;
 found   : List[Contacto]
 required: Contacto

看来listaContantocs,一个不变的List [Contacto]不喜欢返回类型List [Object]。有什么办法可以将List [Object]强制转换为List [Contacto]?

Questioner
ignacio aranguren
Viewed
0
Ivan Stanislavciuc 2020-11-28 23:42:50

你正在组合不同的元素类型List[Contacto]Contacto使用operator ::

以下是你想要的

aux.filter(x=>x.edad<c.edad) ++ (c :: (aux.filter(x=>x.edad>c.edad)))