Convert match statement to partial function when foreach is used

青春壹個敷衍的年華 提交于 2019-12-23 09:48:32

问题


IntelliJ gives me a hint on a following code:

val l = List(0, "1", 2, "3")

l.foreach{_ match {case xx:Int => println(xx);case _ =>}}

The hint is "Convert match statement to partial function"

When I change the foreach to

l.foreach{case x:Int => println(x)}

I get the scala.MatchError exception. I can use collect instead of foreach, however that produces a resulting List which is never used.

Is there some common way how to handle this (something like foreach ignoring the non-matched values), or should I just ignore the hint?


回答1:


Put default case back:

val l = List(0, "1", 2, "3")

l.foreach { case xx:Int => println(xx); case _ => }

IDEA will be happy:

In fact, that is what IDEA will generate if you tap proposed action (ALT+ENTER when your caret points to yellowed text)



来源:https://stackoverflow.com/questions/23760272/convert-match-statement-to-partial-function-when-foreach-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!