将scala映射匹配到对象

时间:2014-10-13 12:45:51

标签: scala scala-2.10

在网络上的所有scala示例中都是这样的

http://www.artima.com/pins1ed/case-classes-and-pattern-matching.html

似乎总是有一个超类。有没有办法避免需要超类或是必要的。例如,我可以做这样的事情......

def matchMe(map: Map[String, String]) {
  map match {
    case searchReq @ SearchQueryRequestParams() => System.out.println("something=" + query)
    //case countReq@CountRequestParams() => System.out.println("count req=" + countReq)
    case _ => System.out.println("match nothing")
  }
}

然而,这不会编译抱怨需要Map [String,String]。我有一个unapply方法,可以使用该参数,如此处所示

trait SearchValidatorBase {
  def unapply(params: Map[String, String]): Option[CommonQueryRequestParams] = {
    val query = params.get("query")
    val fromDateStr = params.get("fromDate")
    val toDateStr = params.get("toDate")
    Some(CommonQueryRequestParams(query, fromDateStr, toDateStr))
  }
}

object CountMatching extends SearchValidatorBase {
  override def unapply(params: Map[String, String]): Option[CountRequestParams] = {
    val result = super.unapply(params)
    val commonParams = result.getOrElse(throw new RuntimeException("bug, should always have a CommonQueryRequestParams"))
    val bucket = params.get("bucket")
    Some(CountRequestParams(commonParams, bucket))
  }
}

object SearchMatching extends SearchValidatorBase {
  override def unapply(params: Map[String, String]): Option[SearchQueryRequestParams] = {
    val result = super.unapply(params)
    val commonParams = result.getOrElse(throw new RuntimeException("bug, should always have a CommonQueryRequestParams"))
    val maxResults = params.get("maxResults")
    val nextToken = params.get("nextToken")
    Some(SearchQueryRequestParams(commonParams, maxResults, nextToken))
  }
}

由于编译器不喜欢我的代码,我做错了吗?

接下来,是否有一种干净的方式来验证并转换为布尔值,Ints等...因为目前我的对象都是Option [String],如下所示

case class CommonQueryRequestParams(
                                         originalQuery: Option[String],
                                         fromDate: Option[String],
                                         toDate: Option[String]
                                         )
case class SearchQueryRequestParams(
                               commonRequest: CommonQueryRequestParams,
                               maxResults: Option[String],
                               nextToken: Option[String])

case class CountRequestParams(commonRequest: CommonQueryRequestParams, bucket: Option[String])

理想情况下,我想将清除错误返回给用户,例如fromDate无效(我希望实际有DateTime,maxResults有Int等等)

感谢, 迪安

1 个答案:

答案 0 :(得分:0)

啊,我没有使用unapply方法的实体,所以这个修复了它

def matchMe(map: Map[String, String]) {
  map match {
    case searchReq @ SearchMatching() => System.out.println("something=" + searchReq)
    //case countReq@CountRequestParams() => System.out.println("count req=" + countReq)
    case _ => System.out.println("match nothing")
  }
}