【发布时间】:2015-12-13 23:10:10
【问题描述】:
我现在有这样的东西:
object Shared {
trait Foo {
type T <: Foo
def +(other: T): T
}
case class IntFoo(value: Int) extends Foo {
type T = IntFoo
def +(other: IntFoo): IntFoo = IntFoo(this.value + other.value)
}
}
object Current extends App {
import Shared._
case class Bar(foo: Foo) {
def +(other: Bar): Bar = Bar(foo + other.foo.asInstanceOf[foo.T])
}
val bar1 = Bar(IntFoo(2))
val bar2 = Bar(IntFoo(3))
val expected = Bar(IntFoo(5))
require(bar1 + bar2 == expected)
println("All OK")
}
这可行,但需要一个 unsafeasInstanceOf,我想在尽可能少地干扰代码的情况下消除它。
我希望编译器能够捕获无效代码,例如:
val otherBar = Bar(StringFoo("asdf"))
val invalidSum = bar1 + otherBar // this throws ClassCastException in runtime
我尝试了以下方法:
case class Bar[FooT <: Foo](foo: FooT) {
def +(other: Bar[FooT]): Bar[FooT] = {
Bar(foo + other.foo)
}
}
但我得到了
Error:(35, 27) type mismatch;
found : other.foo.type (with underlying type FooT)
required: Bar.this.foo.T
Bar(foo + other.foo)
^
建议?
【问题讨论】: