I am creating a Pharo Class method that takes 3 arguments. I am using the following code and it gives me the error "Variable or expression expected.."
MethodName: arg1:argValue1 arg2:argValue2
^ self var1: argValue1 var2: self var3: argValue2
What would be the correct method declaration syntax? Later on, I intend on calling this method like below :
ClassName var1: argValue1 var2: self var3: argValue2
The bit that you have to understand when it comes to naming methods in Smalltalk is that the method can be split into multiple parts, delimited by colons (:
), and that the arguments are inserted after each of those colons. Semantically, that makes a lot of sense, and allows you to use good naming practices so that your code reads almost like an English sentence (which is why the language was named Smalltalk).
So for a method that, in Java or a similar "curly bracket language", might look something like this:
registerUser(String emailAddress, String password, boolean isAdmin) {...}
you would split up the method name in the declaration to fit the arguments, like this:
registerUserWithEmail: anEmailAddress password: aPassword isAdmin: aBoolean
making the method name (often prefixed with #
in Smalltalk because it is registered as a "symbol" in a global dictionary):
#registerUserWithEmail:password:isAdmin:
That whole thing is the method name, and when calling it, you'd insert the appropriate arguments after the colons (let's assume this method is defined in the class UserRegistry
):
UserRegistry
registerUserWithEmail: '[email protected]'
password: 'topSecret'
isAdmin: true
Of course you can leave all that on one line, depending on its length and your readability preferences.
Getting back to your case, you had this:
MethodName: arg1:argValue1 arg2:argValue2
The problem to which your compiler is trying to alert you when it says "Variable or expression expected" is that there's nothing between MethodName:
and arg1:
. I think you may have assumed that MethodName:
wasn't part of the method name but part of the definition.
Some notes:
#methodName:arg1:arg2:
wouldn't make a very good method name in Smalltalk, because the name should describe what it does and, when arguments come into play, what arguments are expected; the same goes for #var1:var2:var3:
ClassName
, then that method needs to be defined on the class side of ClassName
, not on the instance sideself
with one of the arguments being self
as well; ask yourself whether you can simplify something there (hard to be more concrete without knowing what you're trying to do)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With