compose a list of Int from a list of Other Thing in scala

80 views Asked by At

I'm new in SCALA and I want to compose a list of Int from another List call services. this List of Object Service contains a Int field name codeService, and I want to get a List of all codeService from my services list.. I do something like that:

def listaIndicesServicios(servicios: List[Servicio], indices: List[Int]): List[Int]={
if(servicios.length==0){
indices
}
else {
val listaNueva = servicios.head.codigoServicio :: indices
  listaIndicesServicios(servicios.tail, listaNueva)
}
}

and the call my method:

val lista = listaIndicesServicios(servicios.servicios.reverse,List())

But I think that my brain is too imperative yet. and I think that with foldRigth or reduce or something like that I could get a better functional approuch... can you help me thanks

1

There are 1 answers

0
pedrorijo91 On

Use the .map method to transform your List[Service] in a List[Int]. Something like:

servicios.map(servicio => servicio.codigoServicio)

or, scala allows you to write:

servicios.map(_.codigoServicio)