From the course: Build Spring Boot Apps with the Kotlin Programming Language

use as an expression (try with resources)

- The final topic I want to cover in the chapter is Try with resources. This was a construct that was introduced in Java seven. In Java, you could write code like I've got on screen. I'm creating an object of type file input stream inside round brackets immediately after the try statement and before the curly brackets. The idea here, is that in the event of a crash happening, during this code block, any objects that have been declared here will be close automatically. This was quite a nice feature when it was introduced because it avoids having to write some rather horrible nested try finally blocks to ensure our resources are always closed if an exception occurs. So in Kotlin, we can achieve the same thing, that is the automatic closing of resources if an exception occurs, but the syntax is a little different. So I'm going to convert this code to Kotlin so we can see how this would work. So I'm going to create this as a new function, which we'll call Print File. And we won't take any parameters for this function, and it can return nothing. It can be a unit function. So what we want to do is create an object of type file input stream. Let's call that object Input. It's going to be a new file input stream. And we need to give it a file name. I'm not actually going to be running this code, I just want to show you what it would look like. So in Java, we would then surround that line within a try block. We would do something like try open round brackets, have this line in here, and then our code block. So we don't do it like that in Kotlin. Instead you declare the object as normal, but then for that object, you call a method on it called use. And then open a code block. And whilst this code runs within the code block, if that should crash for any reason, I'm just going to put in here, an exception could be thrown here, well then, our input object will be automatically closed, if the exception occurs within a code block defined with a Use statement, then the object will be automatically closed. So that is the syntax to do a Try with resources, or the equivalent of, in Kotlin. Okay, well I think that covers pretty much all we need to talk about regarding exceptions and the try catch block. We will look at custom exceptions a little bit later on, but I want to stress, as we finish this chapter, that because there are no checked exceptions in Kotlin, you really do need to thoroughly test the code that you write. And so in the next chapter, we're going to look at testing. When you're ready, I'll see you there.

Contents