Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this not give a type error?

Tags:

types

scala

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.

like image 665
schmmd Avatar asked Mar 16 '12 17:03

schmmd


People also ask

What is does not name a type error?

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.

How do you fix type errors?

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.

How do you fix a undefined reference in C++?

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++).

What does cout does not name a type mean?

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.


1 Answers

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.

like image 123
drexin Avatar answered Oct 13 '22 03:10

drexin