scala 任一模式匹配
这段代码有什么问题?
(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
隐式类型推断
Left("aoeu")
是Left[String,Nothing]
。您需要明确键入它。看来模式匹配候选者的类型必须始终与所匹配的值相匹配。
为什么它会这样?我怀疑没有充分的理由尝试匹配不兼容的类型。尝试这样做表明开发人员没有编写他们真正想要的内容。编译器错误有助于防止错误。
Implicit typing is inferring that
Left("aoeu")
is aLeft[String,Nothing]
. You need to explicitly type it.It seems that pattern matching candidates must always be of a type matching the value being matched.
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.