为什么我会收到“模式类型与预期类型不兼容”?
我在 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;
}
我收到的错误是:
错误:模式类型与预期类型不兼容; 发现:字符串 必填:单位 情况 y:字符串 => ("\"" + y + "\"")
知道为什么吗?
PS:是否有更高效的方法来编码 myFunction
I came across with an error on my Scala code that I cannot solve by myself (I am new at Scala).
I have the following code:
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;
}
The error I am getting is:
error: pattern type is incompatible with expected type;
found : String
required: Unit
case y:String => ("\"" + y + "\"")
Any idea why?
PS: is there a more performant way to code myFunction
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就原始问题而言,代码无法编译,因为它需要在匹配项周围加上括号,即。
strItems += (item match { ... })
一种更“函数式”的编写方式可能是这样的:
您可能可以使用视图来使其变得懒惰和更“高效” ”,尽管我根本不知道这是否会将两个底层循环 (
map
和mkString
) 合并为一个遍历。In terms of the original question, the code doesn't compile because it requires parentheses around the match, ie.
strItems += (item match { ... })
A more "functional" way of writing this could be something along the lines of:
You could probably use a view to make it lazy and more "performant", although I don't know off the top of my head if that would combine the two underlying loops (
map
&mkString
) into a single traversal.下面是可以编译的代码形式(在 Scala 2.8 中没有任何
JsonSerialized
的定义)以及更简洁的公式(也恰好是无点的):运行的输出这是:
Here's a form of your code that compiles (w/o any definition for
JsonSerializable
) (in Scala 2.8) along with a more succinct formulation (that also happens to be point-free):The output from running this is: