Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala either pattern match

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?

like image 476
ryskajakub Avatar asked Dec 13 '10 19:12

ryskajakub


People also ask

Does Scala have pattern matching?

Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.

What is either in Scala?

In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared.

What is case _ in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .

How pattern matching works in a function's parameter list?

Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values). The same variable name may not be bound more than once in a pattern.


2 Answers

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.

like image 199
Synesso Avatar answered Sep 29 '22 15:09

Synesso


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
like image 23
Knut Arne Vedaa Avatar answered Sep 29 '22 14:09

Knut Arne Vedaa