Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: tracing implicits selection and other code magics

When trying to figure how a library works, implicit conversions are confusing. For example, looking at an expression like 'val foo: Foo = 1', what converts 1 to Foo?

Is it possible to instruct the scala library (or REPL) to print out the code paths that are executing while evaluating an expression?

like image 947
IttayD Avatar asked Dec 29 '22 09:12

IttayD


2 Answers

You can add "-Xprint:typer" to the compiler command line (or "-Ybrowse:typer" for a swing GUI browser) to see the code with the conversions explicitly applied.

like image 146
Mitch Blevins Avatar answered Jan 15 '23 09:01

Mitch Blevins


As an alternative to printing out the conversions, one must realize implicits can't just come out of the blue. You have to bring them into scope in some way. The alternatives are:

  1. Explicit import statement. Watch out for import x.y._ when y is an object, as this is the only way to bring in an implicit into scope.
  2. The object companion of the class that is being converted into something else.
  3. The object companion of the target class, as long as that target is made explicit somehow (such as in your example).

Note that the object scala.Predef is all imported into scope by default, which is how Scala's default implicits get into scope.

like image 35
Daniel C. Sobral Avatar answered Jan 15 '23 10:01

Daniel C. Sobral