Scala - lambda 参数可以匹配元组吗? [英] Scala - can a lambda parameter match a tuple?

查看:50
本文介绍了Scala - lambda 参数可以匹配元组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以说我有一些类似的清单

So say i have some list like

val l = List((1, "blue"), (5, "red"), (2, "green"))

然后我想过滤掉其中一个,我可以做类似的事情

And then i want to filter one of them out, i can do something like

val m = l.filter(item => {
    val (n, s) = item          // "unpack" the tuple here
    n != 2
}

有什么方法可以直接将元组解包"为 lambda 的参数,而不是使用这个中间 item 变量?

Is there any way i can "unpack" the tuple as the parameter to the lambda directly, instead of having this intermediate item variable?

像下面这样的东西是理想的,但是 eclipse 告诉我 参数数量错误;预期=1

Something like the following would be ideal, but eclipse tells me wrong number of parameters; expected=1

val m = l.filter( (n, s) => n != 2 )

任何帮助将不胜感激 - 使用 2.9.0.1

Any help would be appreciated - using 2.9.0.1

推荐答案

这是你能得到的最接近的:

This is about the closest you can get:

 val m = l.filter { case (n, s) => n != 2 }

它基本上是匿名 PartialFunction 中的模式匹配语法.在 Function 对象和特征中也有 tupled 方法,但它们只是这个模式匹配表达式的包装器.

It's basically pattern matching syntax inside an anonymous PartialFunction. There are also the tupled methods in Function object and traits, but they are just a wrapper around this pattern matching expression.

这篇关于Scala - lambda 参数可以匹配元组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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