Search code examples
scalafunctional-programmingyieldfor-comprehension

Create a nested objects from for-comprehension in Scala


I have a case class being instantiated based on some DB operations:

case class FullFight(fight: FightsRow, firstBoxer: BoxersRow,
    secondBoxer: BoxersRow, bookiesOdds: Seq[BookiesOddsRow])

val tupledJoin = for {
    f <- Fights
    b1 <- Boxers if f.firstBoxerId === b1.id
    b2 <- Boxers if f.secondBoxerId === b2.id
} yield (f, b1, b2)

db.run(tupledJoin.result).map(_.map(FullFight.tupled))

The problem is that I would not like to specify any bookiesOdds in this query (they are filled in some other query). Instead I would like to create a tuple tupledJoin containing an empty sequence of Seq[BookiesOddsRow] to create my case class' object. Is there any way of mixing that in a for-comprehension loop? I suppose I need something like that:

val seq: Seq[BookiesOddsRow] = Nil

val tupledJoin = for {
    f <- Fights
    b1 <- Boxers if f.firstBoxerId === b1.id
    b2 <- Boxers if f.secondBoxerId === b2.id
} yield (f, b1, b2, seq)

Is this possible? How to implement it correctly?

Best Regards


Solution

  • I think you can only use DB actions in the for comprehension. You could try this (not tested):

    val tupledJoin = for {
        f <- Fights
        b1 <- Boxers if f.firstBoxerId === b1.id
        b2 <- Boxers if f.secondBoxerId === b2.id
        bookiesOdds <- DBIOAction.successful(Seq())
    } yield (f, b1, b2, bookiesOdds)