Filipe Miranda
Filipe Miranda

Reputation: 944

Iterating or Pattern Matching a element that may have inner lists in Scala

I have the following structure:

case class Something( name: String, more: List[Something] )

Now, you can imagine, that I want to go over all possible elements in this "Tree"

How to do it? I want to perform a Side effect over this structure:

Something("some", List( Something("someMore", Nil), Something("momoMore", Nil), Something("nowIwantToSee", List( ...... a lot more something  ))  ))

And this could go into more and more nesting structures....

???

Upvotes: 1

Views: 45

Answers (2)

oblivion
oblivion

Reputation: 6548

@Jean Logeart has provided a solution that works. Only problem I see is that the function is not tail recursive. You can test that with @tailrec annotation.

You can use pattern matching here as follow:

def traverse(something: Something): Unit = {
    println(something.name)
    something match {
      case Something(name, Nil) =>
      case Something(name, x :: Nil) => traverse(x)
      case Something(name, x :: xs) => traverse(Something(x.name, xs))
    }
  }

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53829

Use recursion:

def recurse(something: Something): Unit = {
  println(something.name)
  something.more.foreach(recurse)
}

So:

> val something = Something("some", List( Something("someMore", Nil), Something("momoMore", Nil), Something("nowIwantToSee", Nil)))
> recurse(something)
some
someMore
momoMore
nowIwantToSee

Upvotes: 1

Related Questions