scala - How to convert nested array to a flat array? -


i have nested array: array("aa", array("bb", "cc"), "dd"). how can convert into: array("aa", "bb", "cc", "dd") in scala?

thanks help!

first of check out inferred type of array:

scala> val arr = array("aa", array("bb", "cc"), "dd") arr: array[java.io.serializable] = array(aa, array(bb, cc), dd) 

scala's collections have single type elements, if put both string , array of strings (or array of array of strings) in array, you'll end array element type that's specific type shared both string , array[string]—in case serializable, pretty useless, since elements of array you'll have cast them other type.

so it's best not situation in first place. you'll more mileage out of type system if don't mix unrelated things in collections. said, if absolutely have this, can write following:

def flattenstringarrays[a](arr: array[a]): array[string] =   arr.flatmap {     case s: string => array(s)     case a: array[_] => flattenstringarrays(a)   } 

and then:

scala> flattenstringarrays(arr) res0: array[string] = array(aa, bb, cc, dd) 

or if "know" you'll ever have 1 level of nesting:

scala> arr.flatmap {      |   case s: string => array(s)      |   case a: array[string] =>      | } res1: array[string] = array(aa, bb, cc, dd) 

but both of these unsafe , unidiomatic.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

spring cloud - How to configure SpringCloud Eureka instance to point to https on non standard port -

javascript - Bootstrap Popover: iOS Safari strange behaviour -