Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't we have capital letters in tuple variable declaration in scala

Why can't we have Capital letter in a tuple variable, As I create a TestData it throws an error

val (trainingData, TestData): Tuple2[RDD[LabeledPoint],RDD[LabeledPoint]] = (splits(0), splits(1))


enter image description here

like image 622
wctapasadan Avatar asked Oct 14 '25 18:10

wctapasadan


2 Answers

This is because you are not creating a ordinary variable in your case.

val (trainingData, TestData) = 

This is deconstructiong the right-hand side expression using the pattern matching on left-hand side. So the variables in pattern matching expressions must start with a lower-case letter.

val (trainingData, TestData) = (split(0), split(1)) 

will be equivalent to

(split(0), split(1)) match {
      case (trainingData, TestData) => (trainingData, TestData)
    }

Which tries to assign the two split values to trainingData, TestData which fails because it always accepts only with the lowercase variable at starting.

Rather, this will works fine

val (trainingData, testData) = (split(0), split(1))

This means,

(split(0), split(1)) match {
      case (trainingData, testData) => (trainingData, testData)
 }

Hope this helps!

like image 128
koiralo Avatar answered Oct 17 '25 07:10

koiralo


In Scala you can create variables with a leading uppercase letter. (It's not recommended, but it can be done.)

val TestCnt = 7

But you can't do that when creating variables via pattern matching.

val (ch, num)       = ('x', 17)  // OK
val (Run, distance) = (true, 5)  // error: not found: value Run

Why is that? It's because the compiler needs to make a distinction between "constant patterns" and "variable patterns." This is explained in some detail in Section 15.2, "Kinds of Patterns" [PiS (1st Edition)], but the gist of it is that a leading uppercase letter is considered a constant, meaning that the pattern must match this value exactly, and a leading lowercase letter is considered a variable, which will match any value and that variable is also bound to the value.

someTuple match {
  case ('t', 42)    => /*will match only if both elements match these values*/
  case (_, TestCnt) => /*will match only if 2nd element same value as TestCnt*/
  case (c, n)       => /*will match any 2-ple, variables c,n bound to values*/
}

It's worth noting that there is a workaround for the lowercase-is-variable rule (use backticks) but there is no way to sidestep the uppercase-is-constant rule.

like image 21
jwvh Avatar answered Oct 17 '25 07:10

jwvh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!