Why is there a difference in behavior between these two pattern matches in a for comprehension?

后端 未结 2 1637
暗喜
暗喜 2020-12-11 08:01

Consider this Map[String, Any]:

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

Now let\'s write a for:

2条回答
  •  执念已碎
    2020-12-11 08:27

    The main reason for the speced behavior is that we want to encourage people to add type annotations, for clarity. If in for comprehensions, they get potentially very costly filter operations instead, that's a trap we want to avoid. However, I agree that we should make it easier to specify that something is a pattern. Probably a single pair of parens should suffice.

    val x: String = y       // type check, can fail at compile time
    val (x: String) = y     // pattern match, can fail at run time
    
    for (x: String <- ys)   // type check, can fail at compile time
    for ((x: String) <- ys) // pattern match, can filter at run time
    

提交回复
热议问题