Arjun Karnwal
Arjun Karnwal

Reputation: 379

Scala Builder a object recursively

Here is the situation

val input = "a:b:c:d:e"

def getTrait(primary: SomeTrait, secondary: SomeTrait): SomeTrait {
...
}

def convertTrait(name: String): SomeTrait {
...
}

So what I want to do is to slide input in window of 2 and build SomeTrait based on that like this

val result = getTrait(convertTrait(a),convertTrait(b))

and then use this result to build another result like this

val resul2 = getTrait(result, convertTrait(c))

and so onn.......

Offcourse I wanna do it in some kind of recursion/for in scala but unable to find solution

Here is where I am

val listOfList = input.split(":").grouped(2).toList



private def builder(inputList: List[List[String]], primary: SomeTrait, secondary: SomeTrait): SomeTrait = {
    for {
      xs <- inputList
      fallback = if(xs.size == 1) providerFallBackChainBuilder(convertTrait(xs(0)), "noop") else providerFallBackChainBuilder(convertTrait(xs(1)), convertTrait(xs(0)))
    } yield fallback
    FallbackConfigProvider(primary, secondary)
  }

I somehow need to pass this fallback back to function .. I know this is not working and not best solution but can anyone guide me on how to dit better and correctly

Upvotes: 0

Views: 63

Answers (2)

Arjun Karnwal
Arjun Karnwal

Reputation: 379

made it to work like this "a:b:c:d:e".split(":").iterator.map(convertTrait).reduce ( (acc, elem) => getTrait(acc, elem) )

Upvotes: 1

This should what you need.

"a:b:c:d:e".split(":").iterator.map(convertTrait).reduce(getTrait)

Upvotes: 2

Related Questions