Scala not found: x value when unpacking return tuple

I have seen such code on countless websites, but it does not seem to compile:

def foo(): (Int, Int) = { (1, 2) } def main(args: Array[String]): Unit = { val (I, O) = foo() } 

It does not work on the marked line, reporting:

  • not found: value I
  • not found: value O

What could be the reason for this?

+6
source share
2 answers

The problem is using the uppercase letters I and O in your template. You should try to replace it with the lowercase letters val (i, o) = foo() . The Scala Language Specification claims that the definition of a value can be extended to match the pattern. For example, the definition of val x :: xs = mylist expands to the following (see page 39):

 val x$ = mylist match { case x :: xs => {x, xs} } val x = x$._1 val xs = x$._2 

In your case, the definition of the value val (i, o) = foo() expands in a similar way. However, the language specification also states that the pattern match contains lowercase letters (see page 114):

The variable x is a simple identifier that begins with a lower letter letter.

+8
source

According to the Scala naming convention ,

The names of methods, values, and variables must be in camelCase with the first lowercase letter:

Your I, O are template variables. However, care must be taken when defining them. By convention, Scala expects template variables to start with a lowercase letter and expects constants to start with an uppercase letter. Thus, the code will not compile.

+3
source

Source: https://habr.com/ru/post/945326/


All Articles