Marcin
Marcin

Reputation: 4333

How do scala implicit values work?

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

Answers (2)

Randall Schulz
Randall Schulz

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

vertti
vertti

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:

  1. Variable has to be marked implicit to be considered as a candidate
  2. Explicit definitions override implicits
  3. Local scope is looked first
  4. Classes companion object is searched if it exists

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

Related Questions