Smalltalk change variable value

653 views Asked by At

I'm learning Smalltalk, but I didn't found any example of how change variable value. How can I do it?

Object subclass: test [
    | testvar |

    "setvalue [
        Function to change value of variable 'testvar'
    ]"

    getvalue [
        ^testvar
    ]
].

Test := test new.
"
How i can set value to testvar?
Transcript show: Test getvalue.
"
1

There are 1 answers

1
Tobias On BEST ANSWER

You can use so-called keyword-messages. You end a method with a colon and put the variable name after that (probably multiple times).

So if you have something like methodFoo(a, b, c) in a curly-brace language, in Smalltalk you typically write

methodFoo: a withSomething: b containing: c

or likewise. This can make method names more readable, too!

Also, getters and setter in Smalltalk typically are named after the variable they are representing. (And classes are typically capitalized while variables are not)

So your example would turn into

Object subclass: Test [
    | testvar |

    testvar: anObject [
        testvar := anObject.
    ]

    testvar [
        ^testvar
    ]
].

test := Test new.
test testvar: 'my value'.
test testvar print.
" prints 'my value' "