scala - Incorrect type inference while pattern matching in Scala
问题描述
In the following ADT, why is Foo
incorrectly inferred for it's type parameter S
?
sealed trait Sum[-S, +A]
case class Foo[S]() extends Sum[S, S]
def execute[S, A](mqtt: Sum[S, A], s: S): A =
mqtt match {
// S and A should be the same for Foo
case Foo() => s // should compile but returns an error.
}
Link on scastie https://scastie.scala-lang.org/xD4RqwKYRW20dy4K0GHEDg
解决方案
You are calling method execute
with two different type parameters S
and A
and compiler has no evidence they are same.
So when you try to return object of type S
when method signature requires A
you get an error. This has nothing to do with ADT.
You can make it work if you give compiler some more details about type parameters.
Such as this def execute[A, S<:A]
推荐阅读
- sql - 在 SQL 中将某些每日时间范围的日期更改为前一天
- java - 带有 Hazelcast 实现 java.io.NotSerializableException 的错误 JCache
- java - 如何在Android中设置默认属性启用禁用
- git - Git责备忽略特定提交
- java - GWT 在单击异常时未显示根调用跟踪
- ios - 如何从“yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ”格式的日期获取日期字符串?
- c# - 如何在单击按钮时实例化数组中的下一个预制件?
- r - 合并两个不同行的表?
- android - Android Firebase SDK Github 认证
- android - 如何在拨出电话期间播放哔声文件并传输到接收器