pattern matching in for comprehension

738 views
Skip to first unread message

Simon Schäfer

unread,
Oct 8, 2012, 9:20:15 AM10/8/12
to scala-l...@googlegroups.com
I just noticed that pattern matching against types does not work in
for-comprehensions:

scala> for (s @ "a" <- List(1,"a","b")) println(s)
a

scala> for (s:String <- List(1,"a","b")) println(s)
<console>:11: error: type mismatch;
found : String => Unit
required: Any => ?
for (s:String <- List(1,"a","b")) println(s)
^

The compiler probably sees it as a normal type ascription, is this
expected behavior?
What's the best way to work around this? The unsugared expression looks
ugly and collect is not best use case because I'm not interested in the
return value.

scala> List(1,"a","b").filter(_.isInstanceOf[String]) foreach println
a
b

scala> List(1,"a","b") collect { case s: String => println(s) }
a
b
res23: List[Unit] = List((), ())


Paul Phillips

unread,
Oct 8, 2012, 9:30:07 AM10/8/12
to scala-l...@googlegroups.com


On Mon, Oct 8, 2012 at 6:20 AM, Simon Schäfer <ma...@antoras.de> wrote:
The compiler probably sees it as a normal type ascription, is this expected behavior?


Here are some ideas from 3.5 years ago when I sort of implemented this:


I am sure there is some reason I haven't finished this, that something made it less of a slam dunk than it appears, but I can neither remember nor google up what that reason is at the moment.

Simon Schäfer

unread,
Oct 8, 2012, 9:48:01 AM10/8/12
to scala-l...@googlegroups.com
Ok, the mentioned workaround works fine. And maybe because Scala now
has virtpatmat there is a reason that could lead to a fix of this
ticket... ;)
Reply all
Reply to author
Forward
0 new messages