Question

Object subclass: Node [     

    |value|

    new [
        Transcript show: 'Test'.
            value := 6.
    ]

    getValue [
        ^value.
    ]

    set:sth [
        value := sth.
    ]

]

|data|
data := Node new.
Transcript show: (data getValue) printString ; cr. "nil"
data set:5.
Transcript show: (data getValue) printString. "5"

The problem is that a new method is never called, so I can not set values or call initialize function. Moreover after something like that:

object := Node new. "Not called"
object new. "Here is called"

the method is called. How to fix that?

Was it helpful?

Solution

#new must be defined on Node class to work:

Object subclass: Node [     

    |value|

    getValue [
        ^value.
    ]

    set: sth [
        value := sth.
    ]

]

Node class extend: [
    new [ | node |
        Transcript show: 'Test'.
        node := (super new).
        node set: 6.
        ^ node
    ]
]

Note that value cannot be accessed from #new in this case, so the setter must be called

OTHER TIPS

As far as I understand you defined new as a method of the instance and not a class.

When you call Node new, a message is sent to a class object Node and it creates an instance of itself that you assign to the object variable. Then when you send new to that variable, a receiver is an instance of Node and has your-defined new

Here is an example on how to add a method to the class in GNU Smalltalk http://www.gnu.org/software/smalltalk/manual/html_node/Defining-methods.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top