coder25
coder25

Reputation: 2393

Concatenate to form list scala

I want to create a list of Test class.

 case class Person(name:String)

   case class Test (desc:String)

   val list =Seq(Person("abc"),Person("def"))
    val s = Option(list)
    private val elems = scala.collection.mutable.ArrayBuffer[Test]()
    val f =for{
      l<-s
    }yield {
      for{
        e <-l
      } yield elems+=tranform(e)

    }
    f.toSeq

    def tranform(p:Person):Test= {
    Test(desc = "Hello "+p.name)
    }

can anyone please help with the following

  1. better way to avoid multiple for
  2. I want to get List(Test("Hello abc"),Test("Hello def")) instead of using ArrayBuffer

Upvotes: 0

Views: 50

Answers (1)

Levi Ramsey
Levi Ramsey

Reputation: 20611

I don't know why you're wrapping a Seq in an Option; Seq represents the no Persons case perfectly well. Is there a difference between None and Some(Seq.empty[Person]) in your application?

Assuming that you can get by without an Option[Seq[Person]]:

list.map(transform).toList

Upvotes: 1

Related Questions