First steps in Scala: Implementing Ruby's Integer.times

Published on September 21, 2011

After reading Seven Languages in Seven Weeks:A Pragmatic Guide to Learning Programming Languages i was left with the desire to know more about a couple of languages, namely Scala and Clojure. While i had some experiences with functional programming (Standard ML, Scheme) and other programming paradigms (Prolog) during the university, now some years have passed.

I strongly suggest you to buy the book even if you already know some of the described languages (Ruby, Io, Prolog, Scala, Erlang, Clojure, Haskell), it only gives a gist of these seven languages in a set of lessons ideally completed in three days (that with some individual unguided experimentation will fill a full week) but with its style will make you hungry for more.

If you need a suggestion on a Scala book, at the moment i’m going through Odersky’s Programming in Scala and up until now it seems a good book even for those without prior experience in functional(ish) languages. Also, unlike other books, the first chapters are free of enigmatic examples that will only confuse beginners.

I’m practicing Scala solving some problems at Project Euler and for one of those i decided to implement something that resembled Ruby’s .times and check the produced java bytecode to get a glimpse of scala’s inner workings.


object scalatimes extends App{
  implicit def int2inttimes(n:Int)=new IntTimes(n)
  
  class IntTimes(n:Int){	
	   def times(what:Int=>Unit){
		   (1 to n).foreach(what);
	   }
  }

  1000.times { n =>
	  val n2=n+1;
	  println(n2);
  }

}

The implementation of times is quite trivial, this code makes use of implicit conversions to add to the Int type the new method through the implicit conversion of Int objects to the new IntTimes in the scope of the scalatimes object.

The times function simply uses the given function object of type Int=>Unit within a foreach cycle, the current index will be accessible inside the function body (i suppose that there are better ways to do this). But what kind of java code does the scala compiler produces for this example? A quick check shows that six class files are built:

  • scalatimes
  • scalatimes$
  • scalatimes$$anonfun$1
  • scalatimes$delayedInit$body
  • scalatimes$Int2
  • scalatimes$IntTimes

These files follow the usual java .class naming conventions,so the scala compiler produces a scalatimes class with a few inner classes. The class files can be decompiled with Jad but the decompiled result will be only partially complete. But anyway, this will help to understand what is happeing behind the scene. As expected, the body of IntTimes is contained in an inner class with the same name:

                                                           
public static class IntTimes
			  implements ScalaObject
{

	public void times(Function1 what)
	{
		Predef$.MODULE$.intWrapper(1).to(n).foreach$mVc$sp(what);
	}

	private final int n;

	public IntTimes(int n)
	{
		this.n = n;
		super();
	}
}    

The times method expects a Function1 object as parameter, the body of the function passed to 1000.times() as parameter has been wrapped in an anonymous inner class (as per Jad comment):

                                                            
/* anonymous class */ 

public static final class anonfun.cls1 
					extends scala.runtime.AbstractFunction1.mcVI.sp
					implements Serializable
{

	public final void apply(int n)
	{
		apply$mcVI$sp(n);
	}

	public void apply$mcVI$sp(int v1)
	{
		int n2 = v1 + 1;
		Predef$.MODULE$.println(BoxesRunTime.boxToInteger(n2));
	}

	public final volatile Object apply(Object v1)
	{
		apply(BoxesRunTime.unboxToInt(v1));
		return BoxedUnit.UNIT;
	}

	public static final long serialVersionUID;

	static 
	{
		0L;
		serialVersionUID = 0L;
	}

} 

The two lines of code that compose the function object body passed to 1000.times() are clearly visible in apply$mcVI$sp(int v1). The main method of the App can be identified in the body of the apply() method of a static class that extends AbstractFunction0:

 
public static final class on0 extends AbstractFunction0
					implements ScalaObject{

	public final Object apply()
	{
		$outer.t1_$eq(System.currentTimeMillis());
		$outer.int2inttimes(1000).outer(new ());
		Predef$.MODULE$.println((new StringBuilder())
						.append("Time:")
						.append(BoxesRunTime.boxToLong(System.currentTimeMillis() - $outer.t1()))
						.toString());
		return BoxedUnit.UNIT;
	}

	private final scalatimes$ $outer;

	public on1.mcVI.sp(scalatimes$ $outer)
	{
		if($outer == null){
			throw new NullPointerException();
		} else {
			this.$outer = $outer;
			super();
			return;
		}
	}
}                                                            

Function0, like the Fuction1 above, is a scala framework object, likely related to the class extended above, and some helper methods in scalatimes hints to the fact that it will be loaded using a delayedInit() call (by an App loader?). And this ends for now my brief and superficial investigation on the structure of the code produced by the Scala compiler.

Did you like this article? Follow me on Twitter!

Receive a notification every time I publish a new article, no spam.

This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.