Reputation: 4333
This is not a question about implicit
in general - I know how it works. It's about one specific construct. Here comes a quite common patten in myBatis for Scala:
manager.readOnly { implicit session => {
//Code block: Do some DB operations in session
}
}
Definition of readOnly
can be found here: https://github.com/mybatis/scala/blob/master/mybatis-scala-core/src/main/scala/org/mybatis/scala/session/SessionManager.scala
How I read it: Call a readOnly
method on manager
with its argument being a function that takes session
as an argument.
My question is: Where implicit session
value is taken from? Which context? I do not have to define any session
object by myself.
Upvotes: 1
Views: 496
Reputation: 26486
My question is: Where implicit session value is taken from? Which context? I do not have to define any session object by myself.
In this example, implicit session
is a formal parameter declaration for the function literal it begins. Thus the actual value is supplied by the code in readOnly
that will invoke that function in carrying out its operation.
Making it implicit here means the code in the function body (which I presume to be a Slick query) wants / needs / prefers an implicit parameter for the sake of notational convenience. (Implicit formal parameters may always have their actual parameter passed explicitly).
Incidentally, the inner braces are unnecessary and should be omitted.
Upvotes: 2
Reputation: 7889
Implicit parameters provide a way to allow parameters of a method to be "found". This means that if a parameter value is not supplied then the compiler will search for an "implicit" value defined within scope according to resolution rules:
Scala documentation puts it this way:
First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition or an implicit parameter. Second, eligible are also all members of companion modules of the implicit parameter’s type that are labeled implicit.
It seems there's also a bunch of edge cases and not a whole lot of good documentation so I don't encourage to go crazy with implicits or you might be in for a surprise.
Upvotes: 3