-2

I have a nested list structure and I want to iterate through the list and print the custom string version of it

 trait Value{
          def myString:String
        }

  case class Student(value: String) extends Value{
    override def myString: String = s"Student =$value"
  }
  case class Employee(value: Double) extends Value{
    override def myString: String = s"Employee =$value"
  }
  case class Department(value: Int) extends Value{
    override def myString: String = s"Dept =$value"
  }

  case class Grp (elements: List[Value] = Nil) extends Value {
    def add (value: Value): Grp = Grp(this.elements ++ List(value))
    override def myString: String = ""
  }

  val group= Grp()
    .add(Student("abc"))
    .add(Employee(100.20))
    .add( Department(10))
    .add( Grp().add( Student("xyz"))) // nested group`e
    .add( Grp().add( Employee("def")))

I want to have the string representation of the group .How to iterate through the group to call myString method

Updated

Output

Student = abc
Employee = 100.20
Department =10
Student =xyz
Employee= def
coder25
  • 2,363
  • 12
  • 57
  • 104

1 Answers1

0

Try this

group.elements.map(_.value.myString).mkString("\n")

Note

Your Grp class is inherits from Value, so the above solution should actually be the value of myString in your group Grp class. Then to get a string representation of Grp, you simply call group.myString.


To clarify,

case class Grp (elements: List[Value] = Nil) extends Value {
    def add (value: Value): Grp = Grp(this.elements ++ List(value))
    override def myString: String = elements match {
        case e::rest => elements.map(_.myString).mkString("\n")
        case _ => ""
    }
}

Now just do groups.myString to get the string

smac89
  • 39,374
  • 15
  • 132
  • 179
  • it doesnt print the nested group value `Student("xyz")` – coder25 Aug 23 '17 at 16:44
  • sry my bad I need to update my question.The actual use case is a bit different – coder25 Aug 23 '17 at 16:47
  • As I was saying in the note, you need to override and specify a value for `myString` in the `Grp` class. That way, the conversion will recursively convert all nested `Grps` to string – smac89 Aug 23 '17 at 16:48
  • I have updated the question.The `Element ` case class is not there,so map wont work as I am not storing as key value pair – coder25 Aug 23 '17 at 16:51
  • @coder25, The `Elements` class had nothing to do with the solution. See my updated answer – smac89 Aug 23 '17 at 16:59
  • `groups.myString` gives empty string and I want to print the value in nested group `Student("xyz")` using its `myString` only – coder25 Aug 23 '17 at 17:03
  • @coder25, Ok I fixed the code. It was just mismatching on match expression – smac89 Aug 23 '17 at 17:38
  • @coder25, it matches a non empty list. The one I had before matches an empty list. So as long as your list contains atleast one value, it will always match – smac89 Aug 23 '17 at 20:00