Home > Mobile >  Scala - Get function result in array inside foreach
Scala - Get function result in array inside foreach

Time:04-08

I want to list the folders from provided source paths. It should go first to 2021 directory get paths and store in array and further to 2022 folder.

Then I need to access this array outside foreach and pass to some other fuction. Unable to figure out how I can go about this. Please help.

val SourcePaths:Array[String] = Array("abfss://[email protected]/testdata/2021/","abfss://[email protected]/testdata/2022/")

SourcePaths.foreach(path=>{
  var allDirPaths:Array[String] = listDirectories(path,true)
})

CodePudding user response:

Use map instead of foreach (also, don't use arrays, they are bad):

val subfolders: Seq[Seq[String]] = sourcePaths.toSeq.map(listDirectories(_, true).toSeq)

Or flatMap if you want all subfolders as one flat list:

val subfolders: Seq[String] = sourceParths.toSeq.flatMap(listDirectories(_, true))
  • Related