我试图将case对象的类型用作抽象类型.我很惊讶地看到下面的(类似)代码编译:
sealed abstract class Bar
case object BarOne extends Bar
case object BarTwo extends Bar
sealed abstract class Foo {
type A <: Bar
def f: A
}
object Foo {
object FooOne extends Foo {
type A = BarOne.type
val f = BarTwo
}
object FooTwo extends Foo {
type A = BarTwo.type
val f = BarOne
}
}
Run Code Online (Sandbox Code Playgroud)
在我的实例中Foo
是参数化并用作案例类.所以我不能只做A
一个类型参数.
怎么f = BarTwo
编译,什么时候A
设置BarOne.type
?
如果A
in f: A
被解释为A <: Bar
,为什么会这样?
有没有办法A
为每个对象实例具体设置Foo
?
我正在使用Scala 2.11.8.
更新:当我val attributeType = ...
用def attributeType = ...
in FooOne
&FooTwo
compilation 替换失败时(如预期的那样).
有人建议您升级到 Scala 的现代版本吗?(玩笑。)
有关覆盖的错误为该类型提供了一个很好的路径。
$ scala
Welcome to Scala 2.12.0-M5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_92).
Type in expressions for evaluation. Or try :help.
scala> :pa
// Entering paste mode (ctrl-D to finish)
sealed abstract class Bar
case object BarOne extends Bar
case object BarTwo extends Bar
sealed abstract class Foo {
type A <: Bar
def f: A
}
object Foo {
object FooOne extends Foo {
type A = BarOne.type
val f = BarTwo
}
object FooTwo extends Foo {
type A = BarTwo.type
val f = BarOne
}
}
// Exiting paste mode, now interpreting.
<console>:26: error: overriding method f in class Foo of type => Foo.FooOne.A;
value f has incompatible type
val f = BarTwo
^
<console>:31: error: overriding method f in class Foo of type => Foo.FooTwo.A;
value f has incompatible type
val f = BarOne
^
Run Code Online (Sandbox Code Playgroud)
这个错误的本质也很聪明:它是由 引入的-Yoverride-objects
,这不是一个非常有用的选项,但出现在我的几个 SO 答案中,现在又出现在一个问题中。
编辑:
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_92).
Type in expressions for evaluation. Or try :help.
scala> object X ; object Y
defined object X
defined object Y
scala> class C { def f: X.type = X }
defined class C
scala> class D extends C { override def f: Y.type = Y }
defined class D
scala> :quit
$ scalam
Welcome to Scala 2.12.0-M5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_92).
Type in expressions for evaluation. Or try :help.
scala> scala> object X ; object Y
// Detected repl transcript. Paste more, or ctrl-D to finish.
defined object X
defined object Y
scala> class C { def f: X.type = X }
defined class C
scala> class D extends C { override def f: Y.type = Y }
defined class D
// Replaying 3 commands from transcript.
scala> object X ; object Y
defined object X
defined object Y
scala> class C { def f: X.type = X }
defined class C
scala> class D extends C { override def f: Y.type = Y }
<console>:13: error: overriding method f in class C of type => X.type;
method f has incompatible type
class D extends C { override def f: Y.type = Y }
^
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
177 次 |
最近记录: |