; case Left(x) => } :6: error:...">

Scala pattern matching

what is wrong with 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 does the template template just not miss the right and check the left?

+5
source share
2 answers

Implicit typing infers what Left("aoeu")is Left[String,Nothing]. You need to explicitly enter it.

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

It seems that candidates for pattern matching should always be of the type matching the matching value.

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 is he acting like that? I suspect that there is no good reason to try to match an incompatible type. Trying to do this is a sign that the developer is not writing what they really intend. A compiler error helps prevent errors.

+11
source
scala> val left: Either[String, String] = Left("foo")
left: Either[String,String] = Left(foo)

scala> left match {
     | case Right(x) => "right " + x
     | case Left(x) => "left " + x }
res3: java.lang.String = left foo
+3

All Articles