Monday, December 27, 2010

Understanding Scala Implicits

Understanding Scala Implicits:

Many languages make use of implicit conversions. Scala is the only language I know of which makes implicit definitions a feature.

It is very easy to understand an implicit conversion since most programming languages do this already for you. Here are two examples (AS3/Java):

trace('Implicitly converted: '+1)
System.out.println('Implicitly converted: '+1);

We only have to care about the expression 'Implicitly converted: '+1 which will result in “Implicitly converted: 1″. Why does this happen? We have a string on the left hand side of the expression and an integer on the right hand side. When the compiler of your choice needs to emit code for this kind of expression it will widen the type of both operands. In this case the resulting type would be String since an implicit conversion from integer to String exists in both ActionScript and Java. If no such conversion exists you would probably get a compile time error.

The compiler inserts this conversion for you. In this example we can make use of an explicit conversion:

trace('Explicitly converted: '+1.toString())
System.out.println('Explicitly converted: '+Integer.toString(1));

[...]

No comments:

Post a Comment