Bimal Kaluarachchi
Bimal Kaluarachchi

Reputation: 23

Read Nested List from Database with relation and Create another List using Scala Recursivly

![enter image description here][1]I have class as it is defined bellow and I read the database fill the records with TbMenu List of TbMenu will be generated.

TbMenu is having its Children list pointing to Parent Id

case class TbMenu(Name:String,Url:String,Children:List[TbMenu]) - Squeryl Database case class

I want to write method to Read above structure recursively and create another list of of object according to following structure

case class MenuBO(Name:String,Url:String,Children:List[TbMenuBO])

It will be really great help to give me some sample implementation of above.

def GenerateMenuData( orgData: List[TbMenu]): List[MenuBO] = { val list: List[MenuBO] = Nil def helper(orgData:List[TbMenu], result:List[MenuBO]): List[MenuBO] = { orgData match{ case x :: tail => { val Menu = new MenuBO(x.id, x.Description, x.ParentId, x.Url, x.haschildren, null) x.children.toList match{ case x:: tail =>{ val Menu2 = new MenuBO(x.id, x.Description, x.ParentId, x.Url, x.haschildren, null) helper(tail, result ::: List(Menu2)) } case Nil => return result} Menu.Children=result helper(tail, result ::: List(Menu)) }case Nil => result }} helper(orgData,list) }

Thank you in advance

Upvotes: 1

Views: 150

Answers (1)

David Frank
David Frank

Reputation: 6092

Assuming that TbMenuBO is the same as MenuBO, the solution can be the following:

def Read(menu: TbMenu): MenuBO = {
  menu match {
    case TbMenu(name, url, children) => MenuBO(name, url, children.map(Read))
  }
}

I suggest you adhering to the official coding conventions (method names and field names should start with lower case characters).

Upvotes: 0

Related Questions