How to map to CaseClass in scala

i'm beginning scala i have this example case class

case class OrderItem(title: String,price: Long,quantity:Int,cover:Option[String],detailJson: String)

and i have List[OrderItem] and List[replaceregex] i want to replace string to list[Orderitem] and i do

val s = OrderItem.flatMap(a => target.map (
      b =>
        if (a.detailJson.contains(start + "\"" + b.unit+ "\""))
          OrderItem(
            a.title,
            a.price,
            a.quantity,
            a.cover,
            a.detailJson.replaceFirst(startregex + b.unit, b.unitreplace))
        else None
      )).filter(_ != None)

and this return List[Product]

Can i Make it to List[Orderitem] from map ? or this my code is bad solution can you tell me pls i'm begining

Upvotes: 0

Views: 51

Answers (1)

Gaël J
Gaël J

Reputation: 15050

This returns a List[Product] because your map operation returns either a OrderItem or a None and the most closer ancestor type for those 2 is Product.

You probably want to always return an Option[OrderItem] in your map and then keep only the defined items thanks to collect:

val s = orderItem
  .flatMap(a =>
    target.map( b =>
      if (...)
        Some(OrderItem(...)))
      else
        None
    )
    .collect { case Some(o) => o }
  )

But wait, as Option extends Seq you can actually just use flatMap and drop the collect like this:

val s = orderItem
  .flatMap(a =>
    target.flatMap(b =>
      if (...)
        Some(OrderItem(...)))
      else
        None
    )
  )

Upvotes: 1

Related Questions