5

I Java I can write this:

Matcher m;
while ((m = pattern.matcher(string)).matches()) {...}

How would I do this in Scala? This doesn't work :

var m: Matcher = null
while ((m = pattern.matcher(s)).matches()) {}

1 Answer 1

9

Assignments return Unit in Scala, but it's ok to use code blocks like this:

while ({
  val m = pattern.matcher(s)
  m.matches
}) { ... }
Sign up to request clarification or add additional context in comments.

3 Comments

If I want to use the val m in the body of the loop?
@Sohaib As I know there's no clean way to do it without using var. But if you're ok with that you may just use this: var m: Matcher = null; while ({ m = pattern.matcher(s); m.matches}) { ... }
yeah, it looks ugly, I always use breakable loop which throws exception. Did they fix it in dotty?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.