1+ package com.baeldung.kotlin
2+
3+ import org.junit.Test
4+ import kotlin.test.assertEquals
5+ import kotlin.test.assertFalse
6+
7+ class LoopTest {
8+
9+ @Test
10+ fun givenLoop_whenBreak_thenComplete () {
11+ var value = 0
12+
13+ for (i in 1 .. 100 ) {
14+ value = i
15+ if (value == 30 )
16+ break ;
17+ }
18+
19+ assertEquals(value, 30 )
20+
21+ outer_loop@ for (i in 1 .. 10 ) {
22+ for (j in 1 .. 10 ) {
23+ value = i * j
24+ if (value == 30 )
25+ break @outer_loop;
26+ }
27+ }
28+
29+ assertEquals(value, 30 )
30+ }
31+
32+ @Test
33+ fun givenLambda_whenReturn_thenComplete () {
34+ listOf (1 , 2 , 3 , 4 , 5 ).forEach {
35+ if (it == 3 ) return // non-local return directly to the caller
36+ assert (it < 3 )
37+ }
38+ // this point is unreachable
39+ assert (false );
40+ }
41+
42+ @Test
43+ fun givenLambda_whenReturnWithExplicitLabel_thenComplete () {
44+ var result = mutableListOf<Int >();
45+
46+ listOf (1 , 2 , 3 , 4 , 5 ).forEach lit@{
47+ if (it == 3 ){
48+ // local return to the caller of the lambda, i.e. the forEach loop
49+ return @lit
50+ }
51+ result.add(it)
52+ }
53+
54+ assert (1 in result
55+ && 2 in result
56+ && 4 in result
57+ && 5 in result)
58+ assertFalse(3 in result)
59+ }
60+
61+ @Test
62+ fun givenLambda_whenReturnWithImplicitLabel_thenComplete () {
63+ var result = mutableListOf<Int >();
64+
65+ listOf (1 , 2 , 3 , 4 , 5 ).forEach {
66+ if (it == 3 ){
67+ // local return to the caller of the lambda, i.e. the forEach loop
68+ return @forEach
69+ }
70+ result.add(it)
71+ }
72+
73+ assert (1 in result
74+ && 2 in result
75+ && 4 in result
76+ && 5 in result)
77+ assertFalse(3 in result)
78+ }
79+ }
0 commit comments