scala 任一模式匹配

发布于 2024-10-07 06:46:42 字数 308 浏览 0 评论 0原文

这段代码有什么问题?

(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]     

为什么模式匹配器不跳过右侧并检查左侧?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生生漫 2024-10-14 06:46:42

隐式类型推断 Left("aoeu")Left[String,Nothing]。您需要明确键入它。

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

看来模式匹配候选者的类型必须始终与所匹配的值相匹配。

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") => ;
            ^

为什么它会这样?我怀疑没有充分的理由尝试匹配不兼容的类型。尝试这样做表明开发人员没有编写他们真正想要的内容。编译器错误有助于防止错误。

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.

且行且努力 2024-10-14 06:46:42
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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文