Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala not found: value x when unpacking returned tuple

Tags:

tuples

scala

I've seen this kind of code on countless websites yet it doesn't seem to compile:

def foo(): (Int, Int) = {
        (1, 2)
}

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

It fails on the marked line, reporting:

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

What might be the cause of this?

like image 892
saarraz1 Avatar asked May 18 '13 15:05

saarraz1


2 Answers

The problem is the use of upper case letters I and O in your pattern match. You should try to replace it by lowercase letters val (i, o) = foo(). The Scala Language Specification states that a value definition can be expanded to a pattern match. For example the definition val x :: xs = mylist expands to the following (cf. p. 39):

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

In your case, the value definition val (i, o) = foo() is expanded in a similar way. However, the language specification also states, that a pattern match contains lower case letters (cf. p. 114):

A variable pattern x is a simple identifier which starts with a lower case letter.

like image 51
Fynn Avatar answered Nov 19 '22 06:11

Fynn


As per Scala naming convention,

Method, Value and variable names should be in camelCase with the first letter lower-case:

Your I, O are pattern variables. However, you have to use caution when defining them. By convention, Scala expects the pattern variables to start with a lowercase letter and expects constants to start with an uppercase letter. So, the code will not compile.

like image 3
Abimaran Kugathasan Avatar answered Nov 19 '22 06:11

Abimaran Kugathasan