Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert one case class to another by using selected element

Tags:

scala

Want to retrieve specific element from the input class while making the list of an output case class.

Example :

case class Student(id:Int, grade:Int, marks:Int)
case class StudentID(id:Int,grade:Int)


val inputList= Option[List(Student(1,100,234) ,Student(2,200,453), Student(3,300,556))]
val outputList=List(StudentID(1,100),StudentID(2,200),StudentID(3,300)) //result

I am trying to get only the id and grade. Please suggest. Also, the problem is input list is Option[].

val a = inputList.iterator.flatMap{ i=> outputList(i.map(_.id)) }
like image 556
CoolGoose Avatar asked Nov 26 '25 12:11

CoolGoose


1 Answers

If the transition from Student-to-StudentID occurs at multiple places throughout the code base, then it might make sense to put the translation logic in the companion object.

case class Student(id:Int, grade:Int, marks:Int)
case class StudentID(id:Int,grade:Int)
object StudentID {
  def apply(s: Student) = new StudentID(s.id, s.grade)
}

val inputList= 
  Option(List(Student(1,100,234) ,Student(2,200,453), Student(3,300,556)))

inputList.map(_.map(StudentID(_)))
//res0: Option[List[StudentID]] =
//  Some(List(StudentID(1,100), StudentID(2,200), StudentID(3,300)))
like image 88
jwvh Avatar answered Nov 29 '25 13:11

jwvh