objectgnu-smalltalk

Not able to create instance of object


I am just starting to use gnu-smalltalk. I have taken following code from here to define a class:

Number subclass: Complex [
       | realpart imagpart |
       "This is a quick way to define class-side methods."
       Complex class >> new [
           <category: 'instance creation'>
           ^self error: 'use real:imaginary:'
       ]
       Complex class >> new: ignore [
           <category: 'instance creation'>
           ^self new
       ]
       Complex class >> real: r imaginary: i [
           <category: 'instance creation'>
           ^(super new) setReal: r setImag: i
       ]
       setReal: r setImag: i [ "What is this method with 2 names?"
           <category: 'basic'>
           realpart := r.
           imagpart := i.
           ^self
       ]
   ]

However, I am not able to create any instances of this class. I have tried various methods and following gives least error!

cn := Complex new: real:15 imaginary:25
cn printNl

The error is:

complexNumber.st:24: expected object

Mostly the error is as follows, e.g. if there is no colon after new keyword:

$ gst complexNumber.st
Object: Complex error: use real:imaginary:
Error(Exception)>>signal (ExcHandling.st:254)
Error(Exception)>>signal: (ExcHandling.st:264)
Complex class(Object)>>error: (SysExcept.st:1456)
Complex class>>new (complexNumber.st:7)
UndefinedObject>>executeStatements (complexNumber.st:25)
nil

Also, I am not clear what is this method with 2 names, each with one argument:

setReal: r setImag: i [  "How can there be 2 names and arguments for one method/function?"
    <category: 'basic'>
    realpart := r.
    imagpart := i.
    ^self
]

I believe usual method should be with one name and argument(s), as from code here :

   spend: amount [
       <category: 'moving money'>
       balance := balance - amount
   ]

Solution

  • To create the Complex number 25 + 25i evaluate

    Complex real: 25 imaginary: 25
    

    How do I know? Because the first part of your question reads

    Complex class >> real: r imaginary: i [
           <category: 'instance creation'>
           ^(super new) setReal: r setImag: i
       ]
    

    Your mistake was to write Complex new: real: 25 imaginary: 25, which doesn't conform to the Smalltalk syntax.

    The Smalltalk syntax for a message with, say, 2 (or more) arguments consists of 2 (or more) keywords, ending with colon, followed, each of them, by the corresponding argument.

    For example, the method setReal: r setImag: i has two keywords, namely setReal: and setImag: and receives two arguments r and i. The name of the method, which in Smalltalk is called its selector is the Symbol that results from concatenating the keywords, in this case setReal:setImag:.