I would expect this to give me a type error since (String, String)
in the else
case is not Pair
.
case class Pair(x: String, y: String)
val value = Console.readLine.toBoolean
val Pair(x, y) =
if (value) Pair("foo", "bar")
else false
Instead, if I enter false, I get the following error at run time.
scala.MatchError: (foo,bar) (of class scala.Tuple2)
I suppose the deconstruction is just sugar for assigning the result to a variable of type Any
and then matching on it, but it seems unfortunate that Scala lets this fly.
The "error does not name a type" in C/C++ is defined as the when user declares outside of the function or does not include it properly in the main file this error will through.
The simplest way is to use the Backspace or Delete key to delete the error. An earlier lesson on basic modifications covered this technique. Word also has a very useful feature called AutoCorrect that corrects common typing errors automatically, as you type.
When we compile these files separately, the first file gives “undefined reference” for the print function, while the second file gives “undefined reference” for the main function. The way to resolve this error is to compile both the files simultaneously (For example, by using g++).
You're missing your main. The code is outside of a function and is considered by the compiler to be either a declaration of variables, class, structs or other such commands.
If you compile this code with scalac -print
you see, what happens. As you correctly supposed, it is just syntactic sugar for a pattern matching. Actually your case class extends Product, which also is a superclass of Tuple2 and that is wh your code compiles. Your value gets assigned to a variable of type Product:
val temp6: Product = if (value)
new Main$Pair("foo", "bar")
else
new Tuple2("foo", "bar");
And then a pattern matching is applied to it:
if (temp6.$isInstanceOf[Main$Pair]())
{
<synthetic> val temp7: Main$Pair = temp6.$asInstanceOf[Main$Pair]();
new Tuple2(temp7.x(), temp7.y())
}
else
throw new MatchError(temp6)
But nontheless this shouldn't compile imho. You should post this to the scala mailing list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With