@@ -10,14 +10,16 @@ class LoopTest {
1010 fun givenLoop_whenBreak_thenComplete () {
1111 var value = 0
1212
13- for (i in 1 .. 100 ) {
13+ // break loop without label
14+ for (i in 1 .. 10 ) {
1415 value = i
15- if (value == 30 )
16+ if (value == 3 )
1617 break ;
1718 }
1819
19- assertEquals(value, 30 )
20+ assertEquals(value, 3 )
2021
22+ // break loop with label
2123 outer_loop@ for (i in 1 .. 10 ) {
2224 for (j in 1 .. 10 ) {
2325 value = i * j
@@ -29,6 +31,31 @@ class LoopTest {
2931 assertEquals(value, 30 )
3032 }
3133
34+ @Test
35+ fun givenLoop_whenContinue_thenComplete () {
36+ var processedList = mutableListOf<Int >()
37+ // continue loop without label
38+ for (i in 1 .. 10 ) {
39+ if (i == 3 )
40+ continue ;
41+ processedList.add(i)
42+ }
43+
44+ assert (processedList.all { it -> it != 3 })
45+
46+ // continue loop with label
47+ processedList = mutableListOf<Int >()
48+ outer_loop@ for (i in 1 .. 10 ) {
49+ for (j in 1 .. 10 ) {
50+ if (i == 3 )
51+ continue @outer_loop;
52+ processedList.add(i* j)
53+ }
54+ }
55+
56+ assertEquals(processedList.size, 90 )
57+ }
58+
3259 @Test
3360 fun givenLambda_whenReturn_thenComplete () {
3461 listOf (1 , 2 , 3 , 4 , 5 ).forEach {
@@ -44,36 +71,51 @@ class LoopTest {
4471 var result = mutableListOf<Int >();
4572
4673 listOf (1 , 2 , 3 , 4 , 5 ).forEach lit@{
47- if (it == 3 ){
74+ if (it == 3 ) {
4875 // local return to the caller of the lambda, i.e. the forEach loop
4976 return @lit
5077 }
5178 result.add(it)
5279 }
5380
54- assert (1 in result
55- && 2 in result
56- && 4 in result
57- && 5 in result)
58- assertFalse(3 in result)
81+ assert (result.all { it -> it != 3 });
5982 }
6083
6184 @Test
6285 fun givenLambda_whenReturnWithImplicitLabel_thenComplete () {
6386 var result = mutableListOf<Int >();
6487
6588 listOf (1 , 2 , 3 , 4 , 5 ).forEach {
66- if (it == 3 ){
89+ if (it == 3 ) {
6790 // local return to the caller of the lambda, i.e. the forEach loop
6891 return @forEach
6992 }
7093 result.add(it)
7194 }
7295
73- assert (1 in result
74- && 2 in result
75- && 4 in result
76- && 5 in result)
77- assertFalse(3 in result)
96+ assert (result.all { it -> it != 3 });
97+ }
98+
99+ @Test
100+ fun givenAnonymousFunction_return_thenComplete () {
101+ var result = mutableListOf<Int >();
102+ listOf (1 , 2 , 3 , 4 , 5 ).forEach(fun (element : Int ) {
103+ if (element == 3 ) return // local return to the caller of the anonymous fun, i.e. the forEach loop
104+ result.add(element);
105+ })
106+
107+ assert (result.all { it -> it != 3 });
108+ }
109+
110+ @Test
111+ fun givenAnonymousFunction_returnToLabel_thenComplete () {
112+ var value = 0 ;
113+ run loop@{
114+ listOf (1 , 2 , 3 , 4 , 5 ).forEach {
115+ value = it;
116+ if (it == 3 ) return @loop // non-local return from the lambda passed to run
117+ }
118+ }
119+ assertEquals(value, 3 )
78120 }
79121}
0 commit comments