[英]Scala type mismatch error
I have a scenario that is causing a type mismatch that I cannot seem to resolve. 我有一种情况导致类型不匹配,我似乎无法解决。 Here's a simplified version of the code: 这是代码的简化版本:
abstract class Msg
trait Channel[M <: Msg] {
def receive(): M
def ack(envelope: M)
}
object ChannelSender {
private var channel : Channel[_ <: Msg] = _
def assignChannel(channel : Channel[_ <: Msg]) = this.channel = channel
def test() {
val msg = channel.receive()
channel.ack(msg) // Type mismatch here
}
}
The error from the compiler is: 来自编译器的错误是:
type mismatch; 类型不匹配; found : msg.type (with underlying type com.msgtest.Envelope) required: _$1 where type _$1 <: com.msgtest.Envelope 找到:msg.type(基础类型为com.msgtest.Envelope)必需:_ $ 1,其中_ $ 1 <:com.msgtest.Envelope
What sort of changes could I make to get this working? 我可以进行哪些更改才能使其正常工作? Additionally, the changes require that the following concrete implementation compile: 此外,更改还要求编译以下具体实现:
class SomeMsg extends Msg
object SomeChannel extends Channel[SomeMsg] {
def receive(): SomeMsg = { null.asInstanceOf[SomeMsg] }
def ack(envelope: SomeMsg) {}
}
object Setup {
ChannelSender.assignChannel(SomeChannel)
}
I could get it to compile under Scala 2.9 with two changes, 我可以通过两个更改使其在Scala 2.9下编译,
trait Channel[M <: Msg] {
type M2 = M // Introduce a type member that's externally visible
def receive(): M2
def ack(envelope: M2)
}
object ChannelSender {
private var channel : Channel[_ <: Msg] = _
def assignChannel(channel : Channel[_ <: Msg]) = this.channel = channel
def test() {
val c = channel // An immutable value, so that c.M2 is stable
val msg = c.receive()
c.ack(msg) // OK now
}
}
The first change is to use an immutable value val c = channel
, so that the path dependent type c.M2
always means the same thing. 第一个更改是使用不变值val c = channel
,因此依赖于路径的类型c.M2
始终具有相同的含义。 The second change is to introduce a type member type M2 = M
in trait Channel
. 第二个更改是在特征Channel
引入类型成员type M2 = M
。 I'm not totally sure why this is necessary (could it be a bug?). 我不太确定为什么这是必要的(可能是错误吗?)。 One thing to note is that c.M2
is a valid type, whereas cM
is undefined. 要注意的一件事是c.M2
是有效类型,而cM
是未定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.