簡體   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