Navigation:  Tutorials > Beginners Guide to Smalltalk > Classes and Methods > Methods >

Answering a result

Previous pageReturn to chapter overviewNext page

We have mentioned previously that all message sends answer a result. This must imply that all methods do so too. A result can be returned from a method by pre-fixing an expression with the ^ character. In this example we are answering the result of the following boolean expression:

x <= aPoint x and: [ y <= aPoint y ]


You can, in fact, return a result from anywhere within a method; you do not have to hold back until the last line. Also, you don't have to explicitly return anything at all. If you omit to include a return (^) expression then, by default, the method will answer the receiving object.

You can learn a lot about Smalltalk just by browsing, so let's take a look at some more methods of class Point. Select the method for #dotProduct:.

dotProduct: aPoint

       "Answer a Number that is the sum of the product of the x coordinates

       and the product of the y coordinates of the receiver and aPoint"


       ^(x * aPoint x) + (y * aPoint y)


This illustrates the definition of a method for a keyword message. In this case it is slightly simpler than the previous example because there is no need to declare any temporary variables. Notice that, in nearly all methods, it is conventional to immediately follow the method header with a comment that describes the purpose of the method. The comment should be indented by one tab space and followed by a single blank line before the body of the method code. Once again this is only convention but following this style will make the code you write easier to understand.

Tip: when describing a particular method to someone we often refer to it using a form like Point>>dotProduct:. This is quite important when you realise that the same message selector can be handled by many different classes.