为什么我得到"模式类型与预期类型不兼容"?

jav*_*ier 4 scala match

我遇到了一个我自己无法解决的Scala代码错误(我是Scala的新手).我有以下代码:

def myFunction(list: List[Any]): String = {
  var strItems : String = "";
  list.foreach(item => {
    strItems += item match {
      case x:JsonSerializable => x.toJson()
      case y:String => ("\"" + y + "\"")
      case _ => item.toString
    }
    if(item != list.last)
      strItems +=  ",";
  })
  strItems;
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

错误:模式类型与预期类型不兼容; found:需要字符串:单位大小写y:String =>("\""+ y +"\"")

知道为什么吗?

PS:有一种更高效的代码来实现myFunction的编码方式

Kri*_*ala 7

就原始问题而言,代码不能编译,因为它需要围绕匹配的括号,即. strItems += (item match { ... })

一种更"实用"的写作方式可能是:

def myFunction(list:List[Any]):String = {
  val strings:List[String] = list.map{
    case x:JsonSerializable => x.toJson()
    case y:String => ("\"" + y + "\"")
    case z => z.toString
  }
  strings.mkString(",")
}
Run Code Online (Sandbox Code Playgroud)

你可能会使用一个视图使它变得懒惰而且更"高效",尽管我不知道如果将两个底层循环(map&mkString)组合成一个遍历的话.

  • 使用`view`会将`map`和`mkString`变成单个遍历. (3认同)