scala - 如何在具有可选参数的函数上进行大小写匹配
问题描述
我希望能够有一个带有可选参数的方法。当存在该可选参数时,它将调用特定的数据库查询,该查询返回使用可选参数过滤的记录。如果该可选参数不存在,我希望它调用不按可选参数过滤的不同数据库查询。
第一个查询尚未编写,但将具有相同的返回结构和类型。编写了第二个查询,并且在没有可选参数和案例的情况下可以正常工作。
def getRecords(id: String, type: String = ""): Future[List[Set[String]]] = {
case Some(type) =>
val query =>
s"""
| ...
""".stripMargin
case _ =>
val query =>
s"""
| ...
""".stripMargin
record = get(dbResult).asList.asScala.map(_.toString).toSet
}
我收到的错误是
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: scala.concurrent.Future[List[Set[String]]]
: Future[List[Set[String]]] = {
^
有人可以向我解释错误的含义吗?以及如何设计我的方法以按照我想要的方式工作?
注意:该方法的一些细节已被省略。它本质上只是返回返回类型的记录以及其中一个查询获取的任何数据。
解决方案
回复你的评论,当然,给你:
def getRecords(id: String, `type`: Option[String] = None): Future[List[Set[String]]] = {
val matchResult = `type` match {
case Some(t) => //t is your string
val query =
s"""
| ...
""".stripMargin
//do something with your query val
case _ =>
val query =
s"""
| ...
""".stripMargin
//do something with your query val
}
//use your matchResult here, whatever that ends up being
//not sure how this works but just copied from your question:
get(dbResult).asList.asScala.map(_.toString).toSet
}
显然你必须在query
某个地方使用,但我假设你只是简化了它。如果您担心空字符串,可以在第一个 case 子句中添加一个保护:case Some(t) if t.nonEmpty => ...
. type
被反引号,因为它是一个关键字。如果您使用非关键字名称,则不需要反引号。
推荐阅读
- python-3.x - 有没有更有效的方法将字符串拆分为整数数组?
- excel - VBA循环。查找更新“之后”值
- c# - 如何在 ASP.NET Core 操作中高效地以 json 和异步方式返回大量值?
- php - 我的 response.php 页面适用于一个页面,但同样不适用于另一个页面
- c - 通过 BLE 发送操纵杆命令
- c# - 从 gulp nunit 运行结果中隐藏 SamlMessageSignature 输出
- collections - 具有相同端点的 API 模拟 Postman 服务器
- export - Filemaker PSOS 导出
- html - Chrome 不会为具有 z-index 和溢出滚动的绝对定位元素的单个子元素显示背景颜色
- haxe - 查找哪个模块导入了另一个模块