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.
list.flatten. If so, why it didn't work for you?flattenwill not work, because list contains different data types, both String and List[String]flattenassumes that list contains another list. So,case listjust uses as it is, andcase xconverts x to list.flattenexample in docs will be helpful: scala-lang.org/api/current/#scala.collection.immutable.ListList[Any]might be anything, so you're loosing type-safety. Could the creation point of this list be changed so that theStrings are wrapped in a List? Like this:List(List("I"), List("can't"), List("do", "this"))instead?