Skip to content

Commit 49f200b

Browse files
authored
Merge pull request #804 from sk1418/the-it-param
[the-it-param] the implicit "it" parameter
2 parents 6b2dd13 + fcedc7b commit 49f200b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.baeldung.itParameter
2+
3+
import org.junit.jupiter.api.Test
4+
import org.slf4j.LoggerFactory
5+
import kotlin.test.assertEquals
6+
7+
class TheItParameterUnitTest {
8+
9+
private val log = LoggerFactory.getLogger(TheItParameterUnitTest::class.java)
10+
11+
@Test
12+
fun `when using it then easy to read`() {
13+
val result = listOf("Kai", "Liam", "Eric", "Kevin")
14+
.filter { it.length == 4 }
15+
.map { it.uppercase() }
16+
.sortedBy { it }
17+
assertEquals(listOf("ERIC", "LIAM"), result)
18+
}
19+
20+
@Test
21+
fun `when using it in nested function blocks then it is not easy to understand`() {
22+
val result = listOf("Kai", "Liam", "Eric", "Kevin").map {
23+
it.map {
24+
(it + 1).also { log.debug("Char After: $it") }
25+
}.joinToString(separator = "")
26+
}
27+
assertEquals(listOf("Lbj", "Mjbn", "Fsjd", "Lfwjo"), result)
28+
}
29+
30+
@Test
31+
fun `when custom functions have only one parameter, then it can be used`() {
32+
fun Long.calc(desc: String, operation: (Long) -> Long) =
33+
"$desc($this) = ${operation(this)}"
34+
35+
val negateOutput = 2L.calc("negate") { -it }
36+
assertEquals("negate(2) = -2", negateOutput)
37+
38+
val squareOutput = 2L.calc("square") { it * it }
39+
assertEquals("square(2) = 4", squareOutput)
40+
}
41+
42+
@Test
43+
fun `when using explict parameters in nested function blocks then it is easy to understand`() {
44+
val result = listOf("Kai", "Liam", "Eric", "Kevin").map { name ->
45+
name.map { originalChar ->
46+
(originalChar + 1).also { resultChar -> log.debug("Char After: $resultChar") }
47+
}.joinToString(separator = "")
48+
}
49+
assertEquals(listOf("Lbj", "Mjbn", "Fsjd", "Lfwjo"), result)
50+
}
51+
52+
@Test
53+
fun `when using deconstruct in lambda function blocks then it is easy to understand`() {
54+
val players = listOf("Kai" to 42, "Liam" to 50, "Eric" to 27, "Kevin" to 49)
55+
val expectedOutput = listOf(
56+
"Kai's score: 42",
57+
"Liam's score: 50",
58+
"Eric's score: 27",
59+
"Kevin's score: 49"
60+
)
61+
62+
val output1 = players.map { "${it.first}'s score: ${it.second}" }
63+
assertEquals(expectedOutput, output1)
64+
65+
// easier to understand:
66+
val output2 = players.map { (player, score) -> "$player's score: $score" }
67+
assertEquals(expectedOutput, output2)
68+
}
69+
70+
}

0 commit comments

Comments
 (0)