Skip to content

Commit 10e9cbd

Browse files
juanvaccarimaibin
authored andcommitted
BAEL-2650 - Kotlin standard functions: run, with, let, also and apply (eugenp#6553)
1 parent 0746c25 commit 10e9cbd

2 files changed

Lines changed: 144 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.scope
2+
3+
data class Student(var studentId: String = "", var name: String = "", var surname: String = "") {
4+
}
5+
6+
data class Teacher(var teacherId: Int = 0, var name: String = "", var surname: String = "") {
7+
fun setId(anId: Int): Teacher = apply { teacherId = anId }
8+
fun setName(aName: String): Teacher = apply { name = aName }
9+
fun setSurname(aSurname: String): Teacher = apply { surname = aSurname }
10+
}
11+
12+
data class Headers(val headerInfo: String)
13+
14+
data class Response(val headers: Headers)
15+
16+
data class RestClient(val url: String) {
17+
fun getResponse() = Response(Headers("some header info"))
18+
}
19+
20+
data class BankAccount(val id: Int) {
21+
fun checkAuthorization(username: String) = Unit
22+
fun addPayee(payee: String) = Unit
23+
fun makePayment(paymentDetails: String) = Unit
24+
25+
}
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package com.baeldung.scope
2+
3+
import org.assertj.core.api.Assertions.assertThat
4+
import org.junit.Test
5+
6+
class ScopeFunctionsUnitTest {
7+
8+
class Logger {
9+
10+
var called : Boolean = false
11+
12+
fun info(message: String) {
13+
called = true
14+
}
15+
16+
fun wasCalled() = called
17+
}
18+
19+
@Test
20+
fun shouldTransformWhenLetFunctionUsed() {
21+
val stringBuider = StringBuilder()
22+
val numberOfCharacters = stringBuider.let {
23+
it.append("This is a transformation function.")
24+
it.append("It takes a StringBuilder instance and returns the number of characters in the generated String")
25+
it.length
26+
}
27+
assertThat(numberOfCharacters).isEqualTo(128)
28+
}
29+
30+
@Test
31+
fun shouldHandleNullabilityWhenLetFunctionUsed() {
32+
33+
val message: String? = "hello there!"
34+
val charactersInMessage = message?.let {
35+
"At this point is safe to reference the variable. Let's print the message: $it"
36+
} ?: "default value"
37+
38+
assertThat(charactersInMessage).isEqualTo("At this point is safe to reference the variable. Let's print the message: hello there!")
39+
40+
val aNullMessage = null
41+
val thisIsNull = aNullMessage?.let {
42+
"At this point it would be safe to reference the variable. But it will not really happen because it is null. Let's reference: $it"
43+
} ?: "default value"
44+
45+
assertThat(thisIsNull).isEqualTo("default value")
46+
}
47+
48+
@Test
49+
fun shouldInitializeObjectWhenUsingApply() {
50+
val aStudent = Student().apply {
51+
studentId = "1234567"
52+
name = "Mary"
53+
surname = "Smith"
54+
}
55+
assertThat(aStudent.name).isEqualTo("Mary")
56+
}
57+
58+
@Test
59+
fun shouldAllowBuilderStyleObjectDesignWhenApplyUsedInClassMethods() {
60+
val teacher = Teacher()
61+
.setId(1000)
62+
.setName("Martha")
63+
.setSurname("Spector")
64+
65+
assertThat(teacher.surname).isEqualTo("Spector")
66+
}
67+
68+
@Test
69+
fun shouldAllowSideEffectWhenUsingAlso() {
70+
val restClient = RestClient("http://www.someurl.com")
71+
72+
val logger = Logger()
73+
74+
val headers = restClient
75+
.getResponse()
76+
.also { logger.info(it.toString()) }
77+
.headers
78+
79+
assertThat(logger.wasCalled()).isTrue()
80+
assertThat(headers.headerInfo).isEqualTo("some header info")
81+
}
82+
83+
@Test
84+
fun shouldInitializeFieldWhenAlsoUsed() {
85+
val aStudent = Student().also { it.name = "John"}
86+
assertThat(aStudent.name).isEqualTo("John")
87+
}
88+
89+
@Test
90+
fun shouldLogicallyGroupObjectCallsWhenUsingWith() {
91+
val bankAccount = BankAccount(1000)
92+
with (bankAccount) {
93+
checkAuthorization("someone")
94+
addPayee("some payee")
95+
makePayment("payment information")
96+
}
97+
}
98+
99+
@Test
100+
fun shouldConvertObjectWhenRunUsed() {
101+
val stringBuider = StringBuilder()
102+
val numberOfCharacters = stringBuider.run {
103+
append("This is a transformation function.")
104+
append("It takes a StringBuilder instance and returns the number of characters in the generated String")
105+
length
106+
}
107+
assertThat(numberOfCharacters).isEqualTo(128)
108+
}
109+
110+
@Test
111+
fun shouldHandleNullabilityWhenRunIsUsed() {
112+
val message: String? = "hello there!"
113+
val charactersInMessage = message?.run {
114+
"At this point is safe to reference the variable. Let's print the message: $this"
115+
} ?: "default value"
116+
assertThat(charactersInMessage).isEqualTo("At this point is safe to reference the variable. Let's print the message: hello there!")
117+
}
118+
119+
}

0 commit comments

Comments
 (0)