user3763116 user3763116 - 3 months ago 22
Scala Question

Writing functional code, example of find function

I am trying to convert the following function according to FP paradigm:

def findByEmail(email: String): User = {
val result = jdbc.find("select * from user where email..")
return result;

My first attempt is the following one:

def findByEmail(email: String): Either[String, Option[User]] = {
try {
val result = jdbc.find("select * from user where email..")
} catch (Exception e) {
return Left(e.getMessage())

if (result == null) return Right(None)


The thing which I do not like is the try which catches all exceptions. Is there any good practice for such things? Is there any better data type rather than String for the left side of either? Is it ok to use the Exception class there?


One way is to flow a Try[User] instead. Then, the caller can match on Success[A] or Failure[Throwable]:

def findByEmail(email: String): Try[User] = Try { jdbc.find("select * from user where email..") }

And then you force the caller to either extract the data from the Try or compose methods on it:

findByEmail("") match {
  case Success(user) => // do stuff
  case Failure(exception) => // handle exception

Or if you want to compose methods:

// If the Try[User] is a Failure it will return it, otherwise executes the function.
findByEmail("").map { case user => // do stuff } 

Another option as @Reactormonk wrote in the comments is to use doobie which is a functional abstraction layer over JDBC for Scala.