Skip to content

Commit c105058

Browse files
authored
[KTLN-650] Add Samples (#952)
1 parent 4bfc291 commit c105058

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

core-kotlin-modules/core-kotlin-advanced-3/pom.xml

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,40 @@
3131
<kotlinx-html-jvm.version>0.7.2</kotlinx-html-jvm.version>
3232
</properties>
3333

34+
<build>
35+
<plugins>
36+
<plugin>
37+
<groupId>org.jetbrains.kotlin</groupId>
38+
<artifactId>kotlin-maven-plugin</artifactId>
39+
<version>${kotlin.version}</version>
40+
<executions>
41+
<execution>
42+
<id>compile</id>
43+
<phase>compile</phase>
44+
<goals>
45+
<goal>compile</goal>
46+
</goals>
47+
<configuration>
48+
<args>
49+
<arg>-Xcontext-receivers</arg>
50+
</args>
51+
</configuration>
52+
</execution>
53+
<execution>
54+
<id>test-compile</id>
55+
<phase>test-compile</phase>
56+
<goals>
57+
<goal>test-compile</goal>
58+
</goals>
59+
<configuration>
60+
<args>
61+
<arg>-Xcontext-receivers</arg>
62+
</args>
63+
</configuration>
64+
</execution>
65+
</executions>
66+
</plugin>
67+
</plugins>
68+
</build>
69+
3470
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.contextreceivers
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
context(StringBuilder)
7+
fun appendHello() {
8+
append("Hello, ")
9+
}
10+
11+
context(StringBuilder)
12+
fun appendWorld() {
13+
append("World!")
14+
}
15+
16+
class HtmlBuilder {
17+
private val elements = mutableListOf<String>()
18+
fun addElement(tag: String, content: String) {
19+
elements.add("<$tag>$content</$tag>")
20+
}
21+
22+
fun build(): String = elements.joinToString("\n")
23+
}
24+
25+
context(HtmlBuilder) fun p(content: String) {
26+
addElement("p", content)
27+
}
28+
29+
context(HtmlBuilder) fun h1(content: String) {
30+
addElement("h1", content)
31+
}
32+
33+
class ContextReceiversUnitTest {
34+
35+
fun html(content: HtmlBuilder.() -> Unit): String {
36+
val builder = HtmlBuilder()
37+
builder.content()
38+
return builder.build()
39+
}
40+
41+
@Test
42+
fun `test StringBuilder context receiver`() {
43+
val builder = StringBuilder()
44+
with(builder) {
45+
appendHello()
46+
appendWorld()
47+
}
48+
assertEquals("Hello, World!", builder.toString())
49+
}
50+
51+
@Test
52+
fun `test HTML DSL with context receivers`() {
53+
val htmlContent = html {
54+
h1("Welcome to My Website")
55+
p("This is a paragraph in my website.")
56+
}
57+
val expected = """
58+
<h1>Welcome to My Website</h1>
59+
<p>This is a paragraph in my website.</p>
60+
""".trimIndent()
61+
assertEquals(expected, htmlContent)
62+
}
63+
64+
}

0 commit comments

Comments
 (0)