Dependency injection in Scala

I (and some others in #scala) have been wondering recently about the state of play for dependency injection in Scala. This is mostly just a brain dump of a few thoughts and a request for feedback. If anyone has any good ideas, please share!

As I see it, most of the Java dependency injection frameworks should work fine for Scala. Guice won’t because of generics issues, and similarly the generics support from other frameworks (e.g. Spring’s type collections) won’t though, so you lose a great deal of type safety. You’re back to an almost Java-like level of type safety in fact. :) Also these don’t take advantage of many of Scala’s great features (higher order functions and a more advanced object system in particular), so the whole thing seems rather unsatisfactory.

I wondered briefly about a system based on abstract method injection using traits, but I couldn’t make it work in a satisfactory manner. The fact that you’d expose dependencies as defs was also unsatisfactory because it means that the compiler doesn’t know that they’re stable so you can’t e.g. import them.

There was some discussion in #scala last night about how “dependency injection is useless if you have higher order functions”. This seems like nonsense to me. A well designed scala program may have less need for DI because of the presence of higher order functions but the basic need for composing of modules (that’s what dependency injection frameworks really are after all – a module composition DSL) is still there, for more or less the same reason why Scala has objects as well as functions.

It’s not entirely clear to me how DI should work in Scala, both from an API and an implementation point of view. Something Guice-like might be a good starting point (but only a starting point! Porting Guice verbatim to Scala would almost certainly be a bad idea), but it’s not clear to me how one would even implement it in Scala. Part of the problem is that Scala lacks a satisfactory metaprogramming facility. It can use Java’s reflection, but the scala.reflect packages seem sadly meager. (There do seem to be a bunch of interesting sounding classes in there, but there appears to be no documentation or evidence of prior usage, so I can’t figure out what on earth they’re for).

This entry was posted in programming and tagged , , , on by .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>