Declaring an object is done as follows.
Object subclass: #Account
instanceVariableNames: 'balance'
classVariableNames: ''
!
The above declaration is a normal Smalltalk method call, Object is the receiver of the message
subclass:#instanceVariableNames:#classVariableNames:#. This represents one method with 3 keyword(named) arguments. The exclamation mark is a delimiter indicating the end of a Smalltalk statement. The basic syntax of method calls is: obj method: arg. This is extended to simple functions such as +, * and -, which are messages to numbers. Account inherits from Object, like everything else in Smalltalk (Object inherits from nil). The above expression declares the Account class.The class
Account now has access to Object's methods, one of them being the primitive method new which creates a new instance of a class. In our Account class we have an instance variable balance that must be initialized to zero at the creation of a new Account. This requires us to override the new method such that it calls an initialization function when new is called.We may open a class and insert methods into it any time we wish, the expression for opening a class is
!ObjectName class methodsFor: 'description'!, the word class decides whether the methods declared operate on instances of the object(if omitted) or the class itself(if included). This expression opens a block, in this block we place a method's declaration, and close the block with an exclamation mark. We now override the new method to initialize newly created Account objects, the initialize method is declared for instances of the Account, setting balance to zero. A method is declared for accessing an Account's balance (^ is the return operator) and one further method is needed to set the balance to whatever we want.!Account class methodsFor: 'instance-creation'!
new
^(super new) initialize
! !
!Account methodsFor: 'initialization'!
initialize
balance := 0
!
balance
^balance
!
balance: x
balance := x
! !
Now, using the Account class.
> a := Account new! an Account > a balance! 0 > a balance: 20! 20 > a balance: 20 + (a balance) 40
As a consequence of the way objects respond to method calls, expressions in Smalltalk are interpreted from left to right with no precedence. It can be suprising if you are used to normal mathematical precedence rules.
> 2+4*3! 18 >2+(4*3)! 14
The remaining Smalltalk syntax is the block. A block is a piece of code between square brackets, blocks represent anonymous functions in Smalltalk. Blocks are called using the
value:# method.> []! a BlockClosure > [:x | x] value: 3! 3 > [:x | x + 1] value: 3! 4 > 1 to: 5 collect: [:x | x + 1]! #(2 3 4 5 6)
This uniform, homoiconic syntax means that extensions in the language are indistinguishable from native syntax and makes metaprogramming very easy, this is why many Smalltalkers say that Smalltalk can incorporate other programming language features simply as libraries.
No comments:
Post a Comment