-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUseExtension.kt
55 lines (48 loc) · 1.29 KB
/
UseExtension.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.arindam.kotlin.x
import com.arindam.kotlin.x.Resource.getFile
import java.io.FileReader
/**
* We deal with resources such as files, network, database connections, streams, etc.,
* all the time and you know the drill...
*
* Step 1: Acquire
* Step 2: Use
* Step 3: Dispose
*
* Let's see how the `.use` extension function makes life easier
*
* Created by Arindam Karmakar on 2019-07-22.
*/
object Resource {
fun getFile(fileName: String): String {
return javaClass.classLoader?.getResource(fileName)?.file ?: String()
}
}
fun main() {
val text = try {
// (1/1) `.use` automatically manages resources that implements the `Closable` interface.
FileReader(getFile("top-secret.txt")).use { it.readText() }
} catch (e: Exception) {
null
}
println(text)
println(busyButNotEffective())
}
/**
* Resource management without the `.use` extension function! Please don't do this.
*/
private fun busyButNotEffective(): String? {
var reader: FileReader? = null
return try {
reader = FileReader(getFile("top-secret.txt"))
reader.readText()
} catch (e: Exception) {
null
} finally {
try {
reader?.close()
} catch (e: Exception) {
/* swallow! 👀 */
}
}
}