在使用foreach时将匹配语句转换为部分函数 [英] Convert match statement to partial function when foreach is used

查看:324
本文介绍了在使用foreach时将匹配语句转换为部分函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IntelliJ给了我一个关于下面的代码的提示:
$ b $ pre $ val $ l List(0,1,2, 3)

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

函数



当我将foreach更改为

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

我得到 scala.MatchError 异常。我可以使用 collect 而不是 foreach ,但是会产生一个结果 List

是否有一些常见的方式来处理这个(像foreach忽略不匹配的值),或者我应该忽略提示?

解决方案

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

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

IDEA会很高兴:


其实这就是如果您点击提议的操作( ALT + ENTER 当您的脱字符指向变黄的文本时),将会生成什么IDEA?


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?

解决方案

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)

这篇关于在使用foreach时将匹配语句转换为部分函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆