Ugly Scala corner case

Eww. I ran into this little wart in the Scala language this morning.  Thank goodness that StackOverflow had an answer, or the frustration might have continued a while longer.   Basically, the wart deals with tuple unwrapping (or matching if you prefer that terminology).  Say that I have some very simple function f that looks like:

[cc lang=’scala’ ]
def f : (Int, Int) = { return (1,2) }
[/cc]

now, in some other piece of code, I want to call f and assign the result to a tuple.

[cc lang=’scala’]
val (Res1, Res2) = f
[/cc]

but wait; Scala complains about this code! You’ll get the following:

error: not found: value Res1
error: not found: value Res2

But why?  The source of the error is that Res1 and Res2 begin with capital letters.  Thus, when Scala tries to assign the tuple elements by means of pattern matching, it assumes that Res1 and Res2 are previously defined constants, not new values (despite the val annotation in front of them).  It’s fairly easy to correct this; just write

[cc lang=’scala’]
val (res1, res2) = f
[/cc]

and you’ll get the expected behavior. However, this seems to me to be a little bit of a wart in the language. Scala is, in my opinion, a beautiful and incredibly expressive language. However, little things like this often remind me that there are still a lot of improvements to be made, and often the little things count.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please insert the signs in the image: