scala break

import org.junit.{Before, BeforeClass, Test}
import org.scalatest.junit.JUnitSuite

import scala.util.control.{Breaks, ControlThrowable}

private class BreakControl extends ControlThrowable

object ScalaBreaksTest {
@BeforeClass
def _init : Unit = {

}
}

class ScalaBreaksTest extends JUnitSuite {

private val breakException = new BreakControl

def init : Unit = ScalaBreaksTest._init

@Before
def inittest() : Unit = {}

@Test
def test1() : Unit = {
var i: Int = 0
try {
while (i < 100) {
i = i + 1
if (i == 5) {
throw breakException
}
}
} catch {
case ex: BreakControl =>
if (ex ne breakException) throw ex
}
println(i)
assert (5 == i, "i must eq 5")
}

@Test
def test2() : Unit = {
val loop = new Breaks

var i: Int = 0
loop.breakable {
while (i < 100) {
i = i + 1
if (i == 5) {
loop.break
}
}
}
println(i)
assert (5 == i, "i must eq 5")
}
}

你可能感兴趣的:(编程语言-Scala)