Domanda

This is a spin-off of the wonderful SO answer here: How do I break out of a loop in Scala?

Why does Scala 2.8+ not allow one to break with a value, which would become the value of the breakable section? This would be often practical.

i.e.

var r= rnd.nextInt(sum)

breakable {
  for( (n,st) <- arr ) {
    if (r<n) break(st)
  } else {
    r -= n
  }
}

instead of (using var with existing library):

var r= rnd.nextInt(sum)
var dest: Station = null

breakable {
  for( (n,st) <- arr ) {
    if (r<n) { dest=st; break }
  } else {
    r -= n
  }
}
dest

I can provide such functionality myself, but was just wondering.

Break documentation is here: http://www.scala-lang.org/api/current/index.html#scala.util.control.Breaks

È stato utile?

Soluzione

The advantage of that over simply creating a def is minimal.

def breaking: Station = {
  for ( (n,st) <- arr ) {
    if (r < n) return st
    else r -= n
  }
  defaultStation
}
breaking

(Granted, I do have an implementation in my set of tools, but it's not something I use that often.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top