App 2: selectAll Database Function

Next, the selectAll function is basically a “read a text file” function, so it’s going to work a lot like the insert function, except we’ll be reading instead of writing. Because the code is similar to the last lesson, I’ll move through it a little more quickly.

First, we know that we want a selectAll function, and it needs to return a Try:

def selectAll(): Try

Because the function returns all rows from the file, this means the success value is a Seq[String]:

def selectAll(): Try[Seq[String]]
                     -----------

In the last lesson I created a writeToFile function, but in this lesson that won’t be necessary, so I’ll add the file-reading code directly to selectAll. Conceptually this code is identical to the previous lesson, except that we’re reading instead of writing:

/**
 * Notice that `dbFilename` comes in through a side door.
 */
def selectAll(): Try[Seq[String]] = 
    var bufferedSource: scala.io.BufferedSource = null
    try
        bufferedSource = Source.fromFile(dbFilename)
        val lines = for line <- bufferedSource.getLines yield line
        Success(lines.toList)
    catch
        case t: Throwable => Failure(t)
    finally
        if bufferedSource != null then bufferedSource.close

Again, I wrote this code in a Java/OOP style, and you can see the “Using” lesson in the Appendix to see the Scala way to write this code.

I tested this function, and in the Success case it returns a value like this:

Success(List("a", "b", "c", "d"))

and in the Failure case it returns an exception like this:

Failure(java.io.FileNotFoundException: example.txt (No such file or directory))

So now we have insert and selectAll functions. I could start working on the UI now, but for the sake of completeness, let’s write a delete function before we switch to the UI.