Boggled with scala.util.matching.Regex

100 views
Skip to first unread message

mar

unread,
Aug 31, 2012, 7:39:42 AM8/31/12
to scala...@googlegroups.com
With these defined..

scala> val t = "this is a test"
t: java.lang.String = this is a test

scala> val rx = " ".r
rx: scala.util.matching.Regex =

0
This works:
scala> val m = rx.findAllIn(t)
m: scala.util.matching.Regex.MatchIterator = non-empty iterator

scala> m.end
res01: Int = 5


.. while this doesn't:
scala> rx.findAllIn(t).end
java.lang.IllegalStateException: No match available

.findAllIIn produces a MatchIterator which has an end-method defined. I fail to see why the last example fails.. :\

Daniel Sobral

unread,
Aug 31, 2012, 11:55:21 AM8/31/12
to mar, scala...@googlegroups.com
Bizarre, I admit, but there's an explanation. The method findAllIn
returns an Iterator -- you need to iterate over it to interact with
it. In the first case, the REPL called "toString" on it, which got it
to check the existence of the first element. In the second case, you
called a method directly without first asserting the existence of the
element.

IMHO, having MatchIterator extend MatchData was a bad design decision
-- Iterators should be Iterators, not Data. As bad design decisions
go, however, this one is mostly harmless -- it mostly breaks broken
code.
--
Daniel C. Sobral

I travel to the future all the time.

mar

unread,
Aug 31, 2012, 1:24:38 PM8/31/12
to scala...@googlegroups.com, mar
That's a great explanation, thank you. A sure "gotcha" if I ever saw one :)

Daniel Sobral

unread,
Aug 31, 2012, 1:33:00 PM8/31/12
to mar, scala...@googlegroups.com
I'm sending this one to Scala Puzzlers! (http://scalapuzzlers.com/index.html)
Reply all
Reply to author
Forward
0 new messages