Skip to content

Commit ee3c3a6

Browse files
alessiostallamaibin
authored andcommitted
BAEL-1402 code for the article: Try-with-resources in Kotlin (eugenp#3418)
1 parent 22dbf2c commit ee3c3a6

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎core-kotlin/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,11 @@
4444
<artifactId>kotlin-stdlib</artifactId>
4545
<version>${kotlin-stdlib.version}</version>
4646
</dependency>
47+
<dependency>
48+
<groupId>org.jetbrains.kotlin</groupId>
49+
<artifactId>kotlin-stdlib-jre8</artifactId>
50+
<version>${kotlin-stdlib.version}</version>
51+
</dependency>
4752
<dependency>
4853
<groupId>org.jetbrains.kotlin</groupId>
4954
<artifactId>kotlin-test-junit</artifactId>
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.baeldung.kotlin
2+
3+
import org.junit.Test
4+
import java.beans.ExceptionListener
5+
import java.beans.XMLEncoder
6+
import java.io.*
7+
import java.lang.Exception
8+
import kotlin.test.assertEquals
9+
import kotlin.test.assertTrue
10+
import kotlin.test.fail
11+
12+
class UseTest {
13+
14+
@Test
15+
fun givenCloseable_whenUseIsCalled_thenItIsClosed() {
16+
val stringWriter = StringWriter()
17+
val writer = BufferedWriter(stringWriter) //Using a BufferedWriter because after close() it throws.
18+
writer.use {
19+
assertEquals(writer, it)
20+
21+
it.write("something")
22+
}
23+
try {
24+
writer.write("something else")
25+
26+
fail("write() should have thrown an exception because the writer is closed.")
27+
} catch (e: IOException) {
28+
//Ok
29+
}
30+
31+
assertEquals("something", stringWriter.toString())
32+
}
33+
34+
@Test
35+
fun givenAutoCloseable_whenUseIsCalled_thenItIsClosed() {
36+
val baos = ByteArrayOutputStream()
37+
val encoder = XMLEncoder(PrintStream(baos)) //XMLEncoder is AutoCloseable but not Closeable.
38+
//Here, we use a PrintStream because after close() it throws.
39+
encoder.exceptionListener = ThrowingExceptionListener()
40+
encoder.use {
41+
assertEquals(encoder, it)
42+
43+
it.writeObject("something")
44+
}
45+
try {
46+
encoder.writeObject("something else")
47+
encoder.flush()
48+
49+
fail("write() should have thrown an exception because the encoder is closed.")
50+
} catch (e: IOException) {
51+
//Ok
52+
}
53+
}
54+
55+
@Test
56+
fun whenSimpleFormIsUsed_thenItWorks() {
57+
StringWriter().use { it.write("something") }
58+
}
59+
}
60+
61+
class ThrowingExceptionListener : ExceptionListener {
62+
override fun exceptionThrown(e: Exception?) {
63+
if(e != null) {
64+
throw e
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)