Search code examples
smalltalkpharo

Class method that makes an object from multiple arguments


In Pharo I want to create a Class Method that creates a new person object and sets a name and age all in one method (two arguments)

Object subclass: #Person
        instanceVariableNames: 'name age'
        classVariableNames: ''
        category: '...'  

However I am unable to access the instance variables within the class method.

name: n : age: a
        "Class method that creates a Person Object and defines its name and age"

        | person1 |
        person1 := self new.
        person1 name := n. "Unable to compile past this point due to red syntax highlighting
        person1 age := a.
        ^person1.

My goal is to be able to call:

aPerson := Person name: 'Pharo' age: '4'

Solution

  • You cannot set instance variables from a class method.

    To solve your problem you could create accessor methods for your instance variables (on the instance side..) and call those from your class side constructor method:

    name: n age: a
        "Class method that creates a Person Object and defines its name and age"
    
        | person1 |
        person1 := self new.
        person1 name: n.
        person1 age: a.
        ^ person1
    

    But for this purpose it is common to code a single instance method to set all the variables and preface its name with set, followed by the variable names:

    setName: aString age: aNumber
        personName := aString.
        age := aNumber.
        ^ self
    

    Now your constructor class method would look like this:

    name: aString  age: aNumber
        ^ self new setName: aString age: aNumber