Scala: tracking implies selection and other magic codes

When you try to understand how the 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 the code paths that are executed when evaluating an expression?

+4
source share
3 answers

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

+7
source

As an alternative to listing conversions, you need to understand that implications can't just get out of hand. You must somehow bring them into scope. Alternatives:

  • Explicit import statement. Beware of import xy_ when y is an object, as this is the only way to introduce an implicit scope.
  • A companion object of the class that is converted to something else.
  • Companion object of the target class, if this target is explicitly made somehow (for example, in your example).

Note that the scala.Predef object is imported into scope by default, which means that Scala implicits falls into scope by default.

+3
source

scalac -print prints code after implicit type conversions where applicable.

 class A{ val x : String = "hi" drop 1 } 

will result in:

 package <empty> { class A extends java.lang.Object with ScalaObject { @remote def $tag(): Int = scala.ScalaObject$class.$tag(A.this); private[this] val x: java.lang.String = _; <stable> <accessor> def x(): java.lang.String = A.this.x; def this(): A = { A.super.this(); A.this.x = scala.this.Predef.forceRandomAccessCharSeq( scala.this.Predef.stringWrapper("hi").drop(1)); () } } } 
0
source