Divide the file name into absolute paths in Scala

Tailored string

val path = "/what/an/awesome/path" 

How can I use Scala to create a list of absolute paths for each directory in the path? The result should be:

List(/what, /what/an, /what/an/awesome, /what/an/awesome/path)

Bonus points for an elegant, functional solution.

+5
source share
5 answers
val path = "/what/an/awesome/path"
val file = new java.io.File(path)
val prefixes = Iterator.iterate(file)(_.getParentFile).takeWhile(_ != null).toList.reverse
+13
source
val path = "/what/an/awesome/path"

scala> path.tail.split("/").scanLeft(""){_ + "/" + _}.tail.toList
res1: List[java.lang.String] = List(/what, /what/an, /what/an/awesome, /what/an/awesome/path)
+8
source

Jesse Eichar Scala IO library ( 0.2.0), , - :

val path  = Path("/what/an/awesome/path")
val paths = (path :: path.parents).reverse

, Path Strings, , , , Path.

, , Scala.

+4
path.drop(1).split("/").foldLeft(List.empty[String])((list, string) => ((list.headOption.getOrElse("") + "/" + string) :: list)).reverse.toList

Probably a cleaner way to use scanLeft, but I couldn't figure it out

+2
source

Fancy-pants regex method:

val R = "(/.*)/".r
(path + '/').inits.collect{case R(x) => x}.toList
+1
source

All Articles