我正在尝试根据 FP 范式转换以下函数:
def findByEmail(email: String): User = {
val result = jdbc.find("select * from user where email..")
return result;
}
我的第一次尝试如下:
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)
Right(result)
}
我不喜欢的是捕获所有异常的 try。这些事情有什么好的做法吗?对于两者的左侧,是否有更好的数据类型而不是 String?可以在那里使用 Exception 类吗?
最佳答案
一种方法是使用 Try[User]
代替。然后,调用者可以匹配 Success[A]
或 Failure[Throwable]
:
def findByEmail(email: String): Try[User] = Try { jdbc.find("select * from user where email..") }
然后强制调用者从 Try
中提取数据或在其上编写方法:
findByEmail("my@mail.com") match {
case Success(user) => // do stuff
case Failure(exception) => // handle exception
}
或者如果你想组合方法:
// If the Try[User] is a Failure it will return it, otherwise executes the function.
findByEmail("my@mail.com").map { case user => // do stuff }
@Reactormonk 在评论中写道的另一个选项是使用 doobie这是 JDBC for Scala 的功能抽象层。
关于scala - 编写功能代码,查找功能示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40260968/