scala either pattern match

coubeatczech picture coubeatczech · Dec 13, 2010 · Viewed 14.8k times · Source

what is wrong in this piece of code?

(Left("aoeu")) match{case Right(x) => ; case Left(x) => }
<console>:6: error: constructor cannot be instantiated to expected type;
 found   : Right[A,B]
 required: Left[java.lang.String,Nothing]     

why the pattern matcher just doesn't skip the Right and examine Left?

Answer

Synesso picture Synesso · Dec 13, 2010

Implicit typing is inferring that Left("aoeu") is a Left[String,Nothing]. You need to explicitly type it.

(Left("aoeu"): Either[String,String]) match{case Right(x) => ; case Left(x) => }

It seems that pattern matching candidates must always be of a type matching the value being matched.

scala> case class X(a: String) 
defined class X

scala> case class Y(a: String) 
defined class Y

scala> X("hi") match {  
     | case Y("hi") => ;
     | case X("hi") => ;
     | }
<console>:11: error: constructor cannot be instantiated to expected type;
 found   : Y
 required: X
       case Y("hi") => ;
            ^

Why does it behave like this? I suspect there is no good reason to attempt to match on an incompatible type. Attempting to do so is a sign that the developer is not writing what they really intend to. The compiler error helps to prevent bugs.