【问题标题】:Match pattern matching based on length of list基于列表长度的匹配模式匹配
【发布时间】:2013-08-19 20:34:34
【问题描述】:

这里的recentest 是一个列表,我想在它的“配置文件”上进行匹配:要么是空的,要么就是一个元素。我可以在 match 语句中本地执行吗?

val newId = if( recentest.size == 0) 0L
    else {recentest(0).as[Long]("item_id") + 1}

【问题讨论】:

  • 请注意,recentest.headOption.fold(0L, _.as[Long]("item_id") + 1)recentest.headOption.map(_.as[Long]("item_id") + 1).getOrElse(0L) 可能会更惯用。

标签: scala idioms


【解决方案1】:

如果你想在几种情况下匹配任意大小,你可以这样做:

list match {
  ...
  case _ if list.length == mySize => ...
  ...
}

【讨论】:

    【解决方案2】:
    val newId = recentest match {
       case Nil    => 0
       case h::Nil => h.as[Long]("item_id") + 1
    }
    

    【讨论】:

    • 你能概括为 2 个(或更多)吗?
    • @aitchnyu ... case Nil => 0; case xs => xs.map(x => x.as[Long]("...")).sum + 1 如果我理解正确的话。也许你只需要 map step 或类似的逻辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多