Monday, February 15, 2010

I require a ... subtle Scala

C++ is complex in part because it is multi-paradigm. That is, C++ supports many styles of programming. It is a rabbit hole, but a necessary one—no one likes to hear "sorry, you can't do that".

Scala is so exciting a follow-on to Java in part because it too is multi-paradigm. Witness Jesse Eichar on self-annotation:

  1. class Base {
  2.   def magic = "bibbity bobbity boo!!"
  3. }
  4. trait Extender extends Base {
  5.   def myMethod = "I can "+magic
  6. }
  7. trait SelfTyper {
  8.   self : Base => 
  9.   
  10.   def myMethod = "I can "+magic
  11. }

But the two are completely different. Extender can be mixed in with any class and adds both the "magic" and "myMethod" to the class it is mixed with. SelfType can only be mixed in with a class that extends Base and SelfTyper only adds the method "myMethod" NOT "magic".

Why is the "self annotations" useful? Because it allows several provides a way of declaring dependencies. One can think of the self annotation declaration as the phrase "I am useable with" or "I require a".

Java is my daily bread and butter (and puts food on the table). There is no easy way in Java to express this subtle point of inheritance—delegation is the closest you come.

In C++ the template system lets you parameterize your base class which you cannot of course do in Java:

template<class T>
class template_base_class : public T
{
};

No comments: