编辑
最初的问题是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 :: _ = xsThis 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
更多推荐
基于集合的多作业
发布评论