Scala for comprehensions/loops and typed patterns

后端 未结 1 625
情歌与酒
情歌与酒 2020-12-11 04:05

According to section 6.19 of the Scala Language Specification this for loop:

for (e <-p) e\'

is translated to:

p <- e         


        
相关标签:
1条回答
  • 2020-12-11 04:34

    The translation you get from specification is actually

    list.withFilter{case b: B => true; case _ => false}.foreach{case b: B => println(b)}
    

    but it still compiles and works. It seems like Scala is losing the case and translating to

    list.withFilter{case b: B => true; case _ => false}.foreach{b: B => println(b)}
    

    which would give the same error.

    This turns out to be a known and old bug: https://github.com/scala/bug/issues/900.

    Workaround provided there:

    object Typed { def unapply[A](a: A) = Some(a) }
    
    for { Typed(b: B) <- list } println(b)
    
    0 讨论(0)
提交回复
热议问题