Search code examples
smalltalkgnu-smalltalk

Smalltalk own new method


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?


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