过滤器的Scala集合类型 [英] Scala collection type for filter

查看:41
本文介绍了过滤器的Scala集合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个 List(1,"1"),它的类型是 List[Any],这当然是正确且符合预期的.现在,如果我像这样映射列表

Assume you have a List(1,"1") it is typed List[Any], which is of course correct and expected. Now if I map the list like this

scala> List(1, "1") map {
     |   case x: Int => x
     |   case y: String => y.toInt
     | }

结果类型是 List[Int] 也是预期的.我的问题是是否有等效于 map for filter 因为以下示例将导致 List[Any].这可能吗?我认为这可以在编译时解决,可能不是运行时?

the resulting type is List[Int] which is expected as well. My question is if there is an equivalent to map for filter because the following example will result in a List[Any]. Is this possible? I assume this could be solved at compile time and possibly not runtime?

scala> List(1, "1") filter {
     |   case x: Int => true
     |   case _ => false
     | }

推荐答案

Scala 2.9:

scala> List(1, "1") collect {
     |   case x: Int => x
     | }
res0: List[Int] = List(1)

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

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