What the code is supposed to do
The function printDouble takes a number and prints twice its value. Calling printDouble(10) from mainFunction should print:
20
The code you start with does not compile:
def printDouble(n: Int): Unit = {
println(2 * num)
}
def mainFunction(): Unit = {
printDouble(10)
}
What goes wrong
The compiler rejects the program with an error like this:
-- [E006] Not Found Error ---
3 | println(2 * num)
| ^^^
| Not found: num
The error names the identifier it could not find, and points at it: num. The function declares a parameter called n. Nothing called num exists anywhere the function can see, so the compiler stops. The program never runs, and nothing is printed.
Why the name has to match
Inside a function body you can use only a few kinds of names: the function's own parameters, values and variables defined inside the body, and names defined in the surrounding scope. A parameter's name is its identity. The line println(2 * num) reads as if num were the number passed in, but the parameter is called n, and Scala treats num and n as unrelated names. Names are also case-sensitive, so N and n would be different too.
This is a very common slip: the idea of "the number" is in the programmer's head under one name, and the code uses another. The compiler cannot guess what you meant, so it reports the first name it cannot resolve.
Fixing it step by step
- Read the error. It says
Not found: numand shows the line. That tells you which name is the problem and where. - Find where the name should come from. The only input to
printDoubleis its parameter, declared in the header asn: Int. - Make the two match. Either use
nin the body, or rename the parameter tonum. Changing the body is the smaller edit. - Leave the call alone.
printDouble(10)passes an argument by position, so the argument does not care what the parameter is called.
The fixed code in Scala
def printDouble(n: Int): Unit = {
println(2 * n)
}
def mainFunction(): Unit = {
printDouble(10)
}
Now 2 * n is 2 * 10, and the program prints 20.
The other fix works equally well. Renaming the parameter to num in the header also makes the names agree:
def printDouble(num: Int): Unit = {
println(2 * num)
}
Either way, the rule is the same: the name used in the body must be the name declared in the header.
Common mistakes
- Fixing the wrong thing. Changing the argument in
printDouble(10)or adding a variablenumelsewhere does not help, because the line that fails is inside the function. - Defining
numinmainFunction. A name defined inside one function is not visible inside another. The body ofprintDoublestill could not see it. - Changing both names to something new. If the header says
numberand the body still saysnum, you have the same error with different names. Check the header and the body together. - Mismatched case.
Nin the body withnin the header fails the same way.
Checking your fix
Run the code in the editor above. A correct fix compiles without errors and prints a single line, 20.
