-
Notifications
You must be signed in to change notification settings - Fork 21
Pattern match in constructor results in extra class member #1913
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
@dragos said: Since vals declared in the class body (or primary constructor) are lexically scoped, they are visible inside methods... therefore they are turned into fields (not talking about the tuple here). What would be a better rule? |
@ijuma said: The problem occurs when you need to compute more than one value inside the block. Most people are surprised when they find out that using pattern matching to assign the values computed in the block (or def) will result in an extra tuple being stored in the class. If the implementation was improved to store the tuple as a local variable in the constructor there would be a simple and predictable way to deal with the described need. |
@dragos said: |
curious if Scala 3 is the same |
Scala 3 does the obvious and deconstructs in the constructor. In this example, C has members x, a, b as expected.
Scala 2 warns
for
but actually there are 2 extra members! Update the ticket! I guess that is why there is another ticket about the tuple member. |
The compiler generates an extra member (a tuple) for the following class as can be seen from the generated byte code below.
The extra field is:
Here is the class definition:
And here is the generated bytecode:
As a general comment on the language itself, I find the feature of class constructors as one of the least thought out parts of the Scala language. Maybe it's because I am new to the language but it's never clear what becomes a field and what doesn't. Also the inability to use local variables in the class constructor (because it will/may become a member variable) is very troubling and restrictive. Basically one is forced to always use the factory pattern (in a companion object) so as to be sure what is going on and so any savings (in conciseness) from the class-constructor feature is nullified.
The text was updated successfully, but these errors were encountered: