首页 > 解决方案 > 如何在具有可选参数的函数上进行大小写匹配

问题描述

我希望能够有一个带有可选参数的方法。当存在该可选参数时,它将调用特定的数据库查询,该查询返回使用可选参数过滤的记录。如果该可选参数不存在,我希望它调用不按可选参数过滤的不同数据库查询。

第一个查询尚未编写,但将具有相同的返回结构和类型。编写了第二个查询,并且在没有可选参数和案例的情况下可以正常工作。

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]]] = {

                              ^

有人可以向我解释错误的含义吗?以及如何设计我的方法以按照我想要的方式工作?

注意:该方法的一些细节已被省略。它本质上只是返回返回类型的记录以及其中一个查询获取的任何数据。

标签: scalaparameterspattern-matchinganonymous-function

解决方案


回复你的评论,当然,给你:

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被反引号,因为它是一个关键字。如果您使用非关键字名称,则不需要反引号。


推荐阅读