Scala flatten列表String和List [String] [英] Scala flatten list of String and List[String]

查看:211
本文介绍了Scala flatten列表String和List [String]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要一些帮助Scala flatten。



我有一个 String List [String]



示例: do,this))



期望的结果: ,do,this)



我做了很多实验,最紧凑的解决方案是:

  val flattenList = list.flatten {
case list:List [Any] =>列表
case x => List(x)
}

但它似乎很棘手,很难理解。对于更幼稚的代码有什么建议?



谢谢。

解决方案

棘手难以理解是同一列表中不同类型的混合元素。这是你的问题的根本原因。一旦你有了,没有办法关于扫描列表,检查每个元素的类型,以纠正它,你的解决方案是一样好(当然,更好,比另一个,建议在其他回答:))。



我真的会重新思考代码路径,导致一个异类列表,如果我是你。这不是一个好方法,因为你颠覆类型安全这种方式,并结束了一个 List [AnyRef] ,可以包含...好,任何东西。


Need some help with Scala flatten.

I have a list of String and List[String].

Example: List("I", "can't", List("do", "this"))

Expecting result: List("I", "can't", "do", "this")

I've done a lot of experiments, and most compact solution is:

val flattenList = list.flatten {
  case list: List[Any] => list
  case x => List(x)
}

But it seems very tricky and hard to understand. Any suggestions for more naive code?

Thanks.

解决方案

What's "tricky and hard to understand" is your mixing elements of different type in the same list. That's the root cause of your problem. Once you have that, there is no way around having to scan the list, and inspect the type of each element to correct it, and your solution to that is as good as any (certainly, better, than the one, suggested in the other answer :)).

I would really rethink the code path that leads to having a heterogeneous list like this in the first place though if I were you. This is not really a good approach, because you subvert the type safety this way, and end up with a List[AnyRef], that can contain ... well, anything.

这篇关于Scala flatten列表String和List [String]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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