Skip to content

Commit af99307

Browse files
nnhai1991@gmail.comnnhai1991@gmail.com
authored andcommitted
LoopTest class
1 parent ed51008 commit af99307

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

  • core-kotlin/src/test/kotlin/com/baeldung/kotlin
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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

Comments
 (0)