If you are a Java developer coming to Kotlin, you might have wondered how to use a language construct that is similar to the try-with-resource statement in Java to automatically close Autocloseable/Closeable resources for you.
Luckily, Kotlin provides the inline extension function use()
that provides similar functionality to the try-with-resource block.
In this tutorial, we will learn how to use the use()
extension function with Autocloseable resources.
At the end of the tutorial, you would have learned:
- How to use the
use()
extension function. - How it differs from the Java try-with-resource statement.
- Basic Kotlin.
- Basic Java IO/NIO concepts.
- A Kotlin IDE such as IntelliJ Community Edition.
To follow along with the tutorial, perform the steps below:
-
Create a new Kotlin project, using JDK 16 as the project JDK and Gradle 7.2 as the build tool.
-
Copy and paste the configuration code below into your
build.gradle.kts
file.import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.5.31" } group = "com.example" version = "1.0-SNAPSHOT" repositories { mavenCentral() } dependencies { testImplementation(kotlin("test")) } tasks.test { useJUnitPlatform() } tasks.withType<KotlinCompile>() { kotlinOptions.jvmTarget = "11" }
-
Under
src/main/kotlin
, create a new package calledcom.example
. -
Under
src/main/kotlin/com/example
, create a new Kotlin file calledEntry.kt
. -
Create the
main()
function inside this file. -
Under
src/main
, create a new source set to contain Java code. -
Under
…src/main/java
, create a new package calledcom.example
.