1
votes

I am working in scala. I went through maximum all the concepts like high ordered function, curried functions, macros etc. But while working with slick i didn't understand this code snippet. db withSession { implicit session =>

What I understood is JdbcBackend.DatabaseDef is calling withSession method. So after that I dont know what is happening in that implementation. Please guys let me know or do I need to know even concepts related to this implementation. Tq

2
That's rather a loan pattern: blog.knoldus.com/2012/11/16/… - cchantep
Thank you simpadjo - M. Akhil

2 Answers

1
votes

You already seem to know the concepts. withSession is a function defined on db that takes a single function as it's argument, i.e. Higher-order function: https://docs.scala-lang.org/tutorials/tour/higher-order-functions.html.html

Scala will allow you to omit the dots when calling that function, i.e. Infix notation: https://docs.scala-lang.org/style/method-invocation.html#infix-notation

The curly brackets just create a standard code block, but as you're using => you end up with a block that defines a function that is then passed to withSession as single argument using the infix notation.

0
votes

withSession method separates business logic from resource management logic. db.withSession provides a connection to the database to a user, then a user can use it, and after the body of withSession block is finished (normally or exceptionally) this connection is returned to the connection pool.

This approach is similar to java's tryWithResource idiom.