Scala + Firebase

A quick overview of using Firebase in a Scala application

First things first, we need to add the Firebase Java SDK to sbt dependencies:

build.sbt

Next, let’s create a Firebase object. With our service accounts credentials in src/main/resources , we can initialize Firebase and create a ref method which can be used by the rest of our application to access our database:

Firebase Setup

Now, let’s say we have the following User class:

Firebase is going to require us to use a plain class with a nullary constructor (i.e. a constructor that doesn’t take any arguments) and getters/setters , which means that we can’t directly use our User case class. However, we can create a plain class with @BeanProperty annotations and then convert this plain class to a case class and vice-versa as needed:

Now that we have our user classes, let’s create a User companion object with methods to create and retrieve users from our database:

To create a User we can just convert from a case class to a plain class using our toBean method:

And when we retrieve a User , we can do the same in reverse, converting from a plain class to a case class using our toCase method:

Finally, let’s import a couple additional modules . . .

so that we can create a method to retrieve a filtered list of Users and return a Map where (userId -> User) :

With all of this in place, we can create a user:

Retrieve a user:

And get a list of users by a specific property: