scala - 编写功能代码,查找功能示例

标签 scala functional-programming

我正在尝试根据 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/

相关文章:

javascript - 是否可以定义中缀函数?

scala - Scala 中的广义结构类型一致性

scala - 自动为类参数制作 setter/getter (以避免案例类)?

scala - 你能就地对可变的 Scala 集合进行排序吗?

.net - 在单行中在 F# 中生成一系列点

functional-programming - 比较 Ocaml 中的两个列表

java - 将 Scala 类(不是案例类)转换为 json

scala - 如何在不导致重新编译的情况下更改 sbt 项目的编译器标志?

haskell - 为什么我的 Haskell 函数参数必须是 Bool 类型?

Haskell:关于部分应用的问题