tags:

views:

141

answers:

2

I am wondering why the following does not work in GNU Smalltalk:

Object subclass: Foo [ ] new printNl

I was expecting a printout of something like "a Foo", but instead gst prints "nil". Doesn't this seem a bit odd?

+2  A: 

This is interpreted as two statements. The first is

Object subclass: Foo [ ]

and the second is

new printNl

where the new variable is undefined so it is nil.

Paolo Bonzini
+2  A: 

Object subclass: Foo [] is not “usual” Smalltalk syntax, it's a recent addition designed to make it practical to code in files. Prior to that there was no dedicated syntax to declare class, since they would be created by a command in the image. Interpreting this code as you expected would be wrong for a couple reasons:

  • First, if subclass: was a real message sent to Object, then Foo should resolve to something, which is not possible since it is just being declared. However, behind the scenes, the compiler does something similar Object subclass: #Foo where #Foo is a symbol for the name of a new class to be created. It would be possible to write all code like that, except then you could not use class names directly (since they don't exist yet when the code is read). You would have to do (Smalltalk at: #Foo) new printNl all over the place. So the whole form Object subclass: Foo [ ] is pure syntax that just declares that this class should be created, and does not mean that at this moment a message should be sent to Object, etc

  • Second, you don't want to create classes in the middle of an algorithm and send them messages immediately, that would be pretty ugly as a development practice. Note that classes have to be registered in the system so that the browser can display them, that the compiler can automatically recompile dependancies, that the version control can record them, etc. Also, what if your code accidentally runs this twice? Should you get a second class Foo and forget about the previous one? So, typically, only the compiler, browser, and other meta-programming tools create new classes, and only at the programmer's request.

Damien Pollet