1

I have been looking at some of the Play Slick examples for building the data access layer and found the following line in the CatDAO example a bit intriguing:

def insert(cat: Cat): Future[Unit] = db.run(Cats += cat).map { _ => () } 

and I wonder what's the purpose of doing .map { _ => () }

UPDATE: running the following in the Scala interpreter provides some clue but still it is not entirely clear why it is needed in the insert method above.

scala> val test = Seq(1, 2, 3)
test: Seq[Int] = List(1, 2, 3)

scala> test map { _ => () }
res0: Seq[Unit] = List((), (), ())
SkyWalker
  • 13,729
  • 18
  • 91
  • 187

1 Answers1

3

Without that mapping db.run method would return a number of records that were inserted into the database (returning type would be Future[Int] then). Yet the author of the code doesn't need that value, and he would like his API to return Future[Unit] instead. That's why he's using that map, which maps Int to Unit in this case (() is a value representing Unit type).

Paweł Jurczenko
  • 4,431
  • 2
  • 20
  • 24
  • Probably it would be then more clear doing `.map { _ => Unit }` a bit more typing for the sake of clarity, or? – SkyWalker Nov 30 '16 at 08:47
  • 1
    Unfortunately this won't work the same, because `Unit` is a type, and `()` is an instance of that type. So your map would return a sequence of types (`Seq[Unit.type]`) and not a sequence of instances of that type (`Seq[Unit]`) – Paweł Jurczenko Nov 30 '16 at 09:55