Scala 任一模式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4432747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scala either pattern match
提问by coubeatczech
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?
为什么模式匹配器不跳过右边并检查左边?
回答by Synesso
Implicit typing is inferring that Left("aoeu")is a Left[String,Nothing]. You need to explicitly type it.
隐式类型推断这Left("aoeu")是一个Left[String,Nothing]. 您需要明确键入它。
(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.
为什么它的行为是这样的?我怀疑没有充分的理由尝试匹配不兼容的类型。尝试这样做表明开发人员没有编写他们真正打算编写的内容。编译器错误有助于防止错误。
回答by Knut Arne Vedaa
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

