Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

scala - How to pattern match into an uppercase variable?

I have a method in Scala that returns a tuple, let's say the method is called 'test'. Then I want to do

val (X,Y) = test()

However, the pattern-matching only works in Scala when the variable names are lowercase, ie:

val(_X,_Y) = test(); val X = _X; val Y = _Y

... works ok, but is ugly, and not terse. Since X and Y are matrices, I don't really want to have to use lowercase variables. (In scipy and matlab, I wouldn't have such a restriction for example).

I think there is some way to make sure lowercase variables behave like uppercase ones, ie by doing `x`. Perhaps there is some way of making uppercase variables behave like lowercase ones? So, that is my question: is there some way of pattern matching directly into uppercase variables in Scala?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The short answer is don't.

Syntax conventions make your code readable and understandable for others. Scala's convention is that variables start with lower-case and constants and classes start with upper-case. By violating this, not only you get problems like pattern-matching issues, your code becomes less readable. (Believe me, if you ever have to read code written by someone else who didn't care for such conventions, you'll be cursing that person.)

If you want to emphasize that the variables are matrices, I suggest you to use xMatrix and yMatrix or something like that. This will make clear that they're variables and that they represent matrices.

Or create a convention specific to your project that all matrix variables will end with let's say "M", like xM and yM.

It's worth typing a few more characters if it makes your code readable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...