2

I have written a little transaction helper that gets passed a closures and executes it within a transaction:

object Transaction {

  val emf = Persistence.createEntityManagerFactory("defaultPersistenceUnit")

  def execute(action: EntityManager => Unit) {
    val em = emf.createEntityManager()
    em.getTransaction.begin()
    action(em)
    em.getTransaction.commit()
    em.close()
  }
}

Then I have an ItemRepository like this:

object ItemRepository {
  def add(implicit entityManager: EntityManager, item: Item) {
    entityManager.persist(item)
  }
}

And finally I want to execute a repository method with the EntityManager passed implicitly:

Transaction.execute(implicit em => ItemRepository.add(item))

But the compiler tells me:

not enough arguments for method add: (implicit entityManager: javax.persistence.EntityManager, implicit item: models.Item)Unit. Unspecified value parameter item.

Everything works if I pass the parameter explicitly:

Transaction.execute(em => ItemRepository.add(em, item))

What's wrong here? It looks pretty much the same as in this answer.

Community
  • 1
  • 1
deamon
  • 89,107
  • 111
  • 320
  • 448

1 Answers1

7

The implicit modifier applies to the whole argument list, not just to one argument. So if you want the entitiyManager argument to be implicit and the item argument not to be implicit, you have to write it like this:

object ItemRepository {
  def add(item: Item)(implicit entityManager: EntityManager) {
    entityManager.persist(item)
  }
}

Otherwise the compiler assumes you want to pass the whole list of parameters explicitly and then complains that there are too few parameters.

Kim Stebel
  • 41,826
  • 12
  • 125
  • 142