Scala 2编译器未强制执行方法类型边界 phantom types约束失效问题
Scala 2幻影类型编译校验异常问题
我无法理解为什么编译器允许当前代码通过编译。
我使用幻影类型(phantom types)保护方法访问权限,只有处于特定"状态"的对象才允许调用对应方法。
绝大多数场景下该不变量都能在编译期正常校验,但部分场景下编译器会直接忽略幻影类型施加的约束,我感觉这是一个严重bug,请问我哪里理解有误?
我已尽可能简化问题,我的实际使用场景更复杂:
class Door[State <: DoorState] private { def doorKey: Int = 1 def open[Phatom >: State <: Closed.type]: Door[Open.type] = new Door[Open.type] def close[Phatom >: State <: Open.type]: Door[Closed.type] = new Door[Closed.type] } object Door { def applyOpenDoor: Door[Open.type] = new Door[Open.type] def applyClosedDoor: Door[Closed.type] = new Door[Closed.type] } sealed trait DoorState case object Closed extends DoorState case object Open extends DoorState
测试代码如下:
val aClosedDoor = Door.applyClosedDoor val res1 = aClosedDoor.close // 编译不通过,符合预期 val res2 = aClosedDoor.open.close.close // 编译不通过,符合预期 println(aClosedDoor.open.close.close) // 编译不通过,符合预期 println(aClosedDoor.open.close.close.doorKey) // 编译不通过,符合预期 aClosedDoor.open.close.close.doorKey == 1 // 编译不通过,符合预期 println(aClosedDoor.open.close.close.doorKey == 1) // 可正常编译!不符合预期
如上所示,调用方可以对已关闭的门执行关闭操作。我的库中对应逻辑会抛出运行时异常,我之前确信该异常受编译期保护,不可能被触发。
我仅在表达式返回布尔值、且该表达式作为函数入参(本例中为println的入参)的场景下能复现该问题。
我暂时不需要替代解决方案,更想知道该问题的成因,请问这是否属于严重缺陷?还是我遗漏了什么知识点?
Scala版本:2.13.5
编辑
在社区讨论后,我已向Scala官方bug仓库提交了问题报告,该问题在Scala 3中不存在。
内容的提问来源于stack exchange,提问作者cmhteixeira
相关产品推荐
相关产品推荐

