7

I have been studying Scala, but what I keep running into is the optimization of syntax. I'm sure that will be great when I am an expert, but until then.. Not so much.

Is there a command or a program that that would add back in all/most of the code that was optimized away? Then I would be able to read the examples, for example.

1

1 Answer 1

9

You can use -print when compiling Scala, and it will print a de-sugared version of the code. Unfortunately, you'll see that Scala has syntactic sugar for good reason.

Let's see a very simple example:

object T { def first[A : Ordering](l: List[A]): A = { val s = l.sorted s(0) } } 

And the output:

package <empty> { final object T extends java.lang.Object with ScalaObject { def first(l: List, evidence$1: scala.math.Ordering): java.lang.Object = { val s: List = l.sorted(evidence$1).$asInstanceOf[List](); s.apply(0) }; def this(): object T = { T.super.this(); () } } } 

You'll often see things like <empty> -- these are compiler annotations, not valid Scala code. For example, a parameter in a case class will have its getter tagged with <stable> <caseaccessor> <accessor> <paramaccessor>. Also, a case class will have a number of methods marked <synthetic>, to indicate they were created by the compiler.

Also, the this constructor you see here is not valid Scala code, exactly. In this case, the "normal" Scala constructor (which is the body of the class, trait or object) is moved inside such a this method -- which is how Java itself sees things.

So, this is mixture of Scala and Java, with a bit of compiler internals sprinkled over it. But it will show the de-sugared stuff.

1
  • cool, i'll have to play with that. Maybe it will help with examples from the books I can't follow. Commented Aug 12, 2011 at 1:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.