繁体   English   中英

Scala类型不匹配错误

[英]Scala type mismatch error

我有一种情况导致类型不匹配,我似乎无法解决。 这是代码的简化版本:

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
  }
}

来自编译器的错误是:

类型不匹配; 找到:msg.type(基础类型为com.msgtest.Envelope)必需:_ $ 1,其中_ $ 1 <:com.msgtest.Envelope

我可以进行哪些更改才能使其正常工作? 此外,更改还要求编译以下具体实现:

class SomeMsg extends Msg

object SomeChannel extends Channel[SomeMsg] {
  def receive(): SomeMsg = { null.asInstanceOf[SomeMsg] }
  def ack(envelope: SomeMsg) {}
}

object Setup {
  ChannelSender.assignChannel(SomeChannel)
}

我可以通过两个更改使其在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
  }
}

第一个更改是使用不变值val c = channel ,因此依赖于路径的类型c.M2始终具有相同的含义。 第二个更改是在特征Channel引入类型成员type M2 = M 我不太确定为什么这是必要的(可能是错误吗?)。 要注意的一件事是c.M2是有效类型,而cM是未定义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM