6

A silly, syntactical question:

If the assignment operator is really a function, like

def value=(x)
  @value = x
end

without a space between the left-hand operand and the "=", then why can the assignment be made as test.value = x (with a space), but the method definition cannot be written as:

def value = (x)
  @value = x
end

with the space. Is this simply syntax dictated by the parser?

1
  • 1
    You might ask as well, "If the milk is white, why the sky isn't?.." Commented Feb 10, 2011 at 22:29

2 Answers 2

6

def needs to be followed by a token for the function name, optionally followed by an argument list. The parenthesis on the argument list is optional (e.g., def value= x is an appropriate definition). def value = (x) looks like def followed by two tokens and then an argument list, which does not parse.

Sign up to request clarification or add additional context in comments.

8 Comments

The parser is smart enough to know that the statement test.value = x is not a token followed by two passed parameters. Why doesn't it parse the method definition similarly?
@inyourcorner but you aren't relying on the def keyword in your example
@inyourcorner: That is entirely different from function definition. The handler for assignment knows to check for value= methods in the receiving object (parsing is not involved).
@cam: Can you pass an operator as a parameter then? My point being, why wouldn't the parser recognize the first operator being the operator operating on the operand?
@inyourcorner: I'm not sure what you mean. Operators are not objects so it doesn't make sense to "pass" them.
|
1

That's parser/interpreter magic.

When the interpreter sees the assignment looks for a matching method.

I agree with you in this regard ( almost ), I think the assignment should be some.value= x ( without space between 'value' and '=' ) always.

Scala does something similar but uses an underscore def value_= ( x: X )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.