[英]Why can I not create a new subclass and use it in the same sentence?
I am wondering why the following does not work in GNU Smalltalk: 我想知道为什么以下在GNU Smalltalk中不起作用:
Object subclass: Foo [ ] new printNl
I was expecting a printout of something like "a Foo", but instead gst prints "nil". 我期待打印输出类似“a Foo”的东西,但gst打印“nil”。 Doesn't this seem a bit odd? 这看起来有点奇怪吗?
This is interpreted as two statements. 这被解释为两个陈述。 The first is 首先是
Object subclass: Foo [ ] 对象子类:Foo []
and the second is 第二是
new printNl new printNl
where the new variable is undefined so it is nil. 新变量未定义的地方,因此它是零。
Object subclass: Foo []
is not “usual” Smalltalk syntax, it's a recent addition designed to make it practical to code in files. Object subclass: Foo []
不是“通常的”Smalltalk语法,它是最近添加的,旨在使文档中的代码实用化。 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. 首先,如果subclass:
是发送给Object
的真实消息,那么Foo
应该解析为某些东西,这是不可能的,因为它只是被声明。 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. 但是,在幕后,编译器会执行类似的Object subclass: #Foo
,其中#Foo
是要创建的新类名称的符号。 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. 你不得不做(Smalltalk at: #Foo) new printNl
都是。 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 所以整个形式的Object subclass: Foo [ ]
是纯语法,只是声明应该创建这个类,并不意味着此时应该将消息发送给Object
等
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? 如果你得到第二堂课Foo而忘记前一堂课? So, typically, only the compiler, browser, and other meta-programming tools create new classes, and only at the programmer's request. 因此,通常,只有编译器,浏览器和其他元编程工具才能创建新类,并且只能在程序员的请求下创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.