基于集合的多作业 [英] Multi-Assignment based on Collection

查看:114
本文介绍了基于集合的多作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑



最初的问题是Collection to Tuple,因为我假设我需要一个元组才能进行可变的多重赋值。事实证明,可以直接对集合进行可变的多重赋值。


有一个简单的Seq [String]派生自一个正则表达式,我想转换为



我目前有:

这是最直接的方法是什么?

  val(clazz,date)= captures match {
case x:Seq [String] =& (x(0),x(1))
}

我的路由层有一堆regex匹配的路由,我将做val(a,b,c)多重赋值on(捕获组总是知道,因为如果regex不匹配路由不处理)。比较匹配{case .. => ..}会更好一个精简的解决方案



在Scala中将集合转换为元组最短的1-liner是什么? p>

解决方案

这不是问题的答案,但可能以不同的方式解决问题。



你知道你可以匹配 xs:List [String] ,如下所示:

  val a :: b :: c :: _ = xs 

这将列表的前三个元素分配给 a,b,c ?您可以在 val 的声明中匹配 Seq 的其他内容,就像在 语句。请务必注意匹配的错误:



Scala模式匹配和try / catch


Edit

originally the question was "Collection to Tuple" as I assumed I needed a tuple in order to do variable multi-assignment. It turns out that one can do variable multi-assignment directly on collections. Retitled the question accordingly.

Original Have a simple Seq[String] derived from a regex that I would like to convert to a Tuple.

What's the most direct way to do so?

I currently have:

val(clazz, date) = captures match {
  case x: Seq[String] => (x(0), x(1))
}

Which is ok, but my routing layer has a bunch of regex matched routes that I'll be doing val(a,b,c) multi-assignment on (the capture group is always known since the route is not processed if regex does not match). Would be nice to have a leaner solution than match { case.. => ..}

What's the shortest 1-liner to convert collections to tuples in Scala?

解决方案

This is not an answer to the question but might solve the problem in a different way.

You know you can match a xs: List[String] like so:

val a :: b :: c :: _ = xs 

This assigns the first three elements of the list to a,b,c? You can match other things like Seq in the declaration of a val just like inside a case statement. Be sure you take care of matching errors:

Scala pattern matching and try/catch

这篇关于基于集合的多作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆