为什么在 for comprehension 中这两种模式匹配之间的行为存在差异? [英] Why is there a difference in behavior between these two pattern matches in a for comprehension?

查看:33
本文介绍了为什么在 for comprehension 中这两种模式匹配之间的行为存在差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个Map[String, Any]:

val m1 = Map(("k1" -> "v1"), ("k2" -> 10))

现在让我们写一个for:

scala> for ((a, b) <- m1) println(a + b)
k1v1
k210

到目前为止一切顺利.

现在让我们指定第二个成员的类型:

Now let's specify the type of the second member:

scala> for ((a, b: String) <- m1) println(a + b)
k1v1

scala> for ((a, b: Integer) <- m1) println(a + b)
k210

在这里,当我指定一个类型时,会进行过滤,这很棒.

Here, as I specify a type, filtering takes place, which is great.

现在说我想使用 Array[Any] 代替:

Now say I want to use an Array[Any] instead:

val l1 = Array("a", 2)

在这里,事情破裂了:

scala> for (v: String <- l1) println(v)
<console>:7: error: type mismatch;
 found   : (String) => Unit
 required: (Any) => ?

我的双重问题是:

  • 为什么第二个匹配过滤器不匹配?
  • 有没有办法在不使用脏的 isInstanceOf 的情况下在第二种情况下表达这种过滤?
  • why doesn't the second match filter as well?
  • is there a way to express such filtering in the second scenario without using a dirty isInstanceOf?

推荐答案

好吧,后一个示例不起作用,因为它没有被指定.有一些关于什么是合理行为的讨论.就个人而言,我希望它像你一样工作.事情是这样的:

Well, the latter example doesn't work because it isn't spec'ed to. There's some discussion as to what would be the reasonable behavior. Personally, I'd expect it to work just like you. The thing is that:

val v: String = (10: Any) // is a compile error
(10: Any) match {
    case v: String =>
} // throws an exception

如果您对此不相信,请加入俱乐部.:-) 这是一个解决方法:

If you are not convinced by this, join the club. :-) Here's a workaround:

for (va @ (v: String) <- l1) println(v)

请注意,在 Scala 3 中,您可以:

Note that in Scala 3, you can:

for (case v: String <- l1) println(v)

这篇关于为什么在 for comprehension 中这两种模式匹配之间的行为存在差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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