"I have a mind like a steel... uh... thingy." Patrick Logan's weblog.

Search This Blog

Saturday, June 09, 2007

Scala Implicits

I am continuing on my Scala learning curve. Scala continues to feel like a pragmatic sweet spot among programming languages. My most recent find is "implicits".

One of the pleasing aspects of dynamic languages like Common Lisp and Smalltalk (and so Python and Ruby) is the ability to extend objects that the system or some other programmers implemented, as if they were your own.

Languages without this capability force programmers to create "utility" classes. These extensions would have been in Object or String or Whatever, but the language would not allow extensions, so, here, take this StringUtils class or WhateverUtils class and use that with a String argument or a Whatever argument.

Scala is compile-time type checked (with type inference along the lines of ML and Haskell), so getting into the guts of a class and mucking at runtime is not so desirable from a type-safety point of view, and not so easy to make type-safe from an implementor's point of view. (Or maybe it's just not a priority for the language designers.)

Yet Scala does provide extensions of a sort, via a mechanism called "implicits". Extensions are defined in "wrapper" classes and an implicit type conversion is defined such that when an undefined method is encountered on an object, the defined implicit conversions are searched for a definition of that method. The object is essentially "wrapped" in an instance of that other class, and the method is invoked on the instance.

While this is type safe, it is not nearly as powerful as those mechanisms in the popular dynamic languages. (For one small example, it does not allow wrapping or replacing existing methods, as far as I can tell.) Still it does provide a fairly simple extension mechanism and so makes a fairly common situation much more pleasing than for the most popular type-checked languages.

1 comment:

Dan Sickles said...

Groovy has an interesting new class extension story.

Blog Archive

About Me

Portland, Oregon, United States
I'm usually writing from my favorite location on the planet, the pacific northwest of the u.s. I write for myself only and unless otherwise specified my posts here should not be taken as representing an official position of my employer. Contact me at my gee mail account, username patrickdlogan.