[英]Mismatch between call-by-name parameter and function type
在以下情況下,by-name參數導致與功能沖突。
給定一些序列化基礎結構:
trait Tx {
def readSource[A](implicit ser: Serializer[A]) : Source[A] =
new Source[A] {
def get(implicit tx: Tx): A = ser.read(new In {})
}
}
trait In
trait Source[A] { def get(implicit tx: Tx): A }
trait Serializer[A] { def read(in: In)(implicit tx: Tx): A }
還有一個示例類型及其序列化器:
// needs recursive access to itself. for reasons
// beyond the scope of this questions, `self` must
// be a by-name parameter
class Transport(self: => Source[Transport])
// again: self is required to be by-name
def transportSer(self: => Source[Transport]) : Serializer[Transport] =
new Serializer[Transport] {
def read(in: In)(implicit tx: Tx): Transport = new Transport(self)
}
現在想象一下一個名為Hook
的包裝器,該包裝器處理遞歸/相互連接:
trait Hook[A] {
def source: Source[A]
}
及其序列化器:
def hookSer[A](peerSelf: Source[A] => Serializer[A]) : Serializer[Hook[A]] =
new Serializer[Hook[A]] {
def read(in: In)(implicit tx: Tx) : Hook[A] =
new Hook[A] with Serializer[A] {
val source: Source[A] = tx.readSource[A](this)
def read(in: In)(implicit tx: Tx) : A = peerSelf(source).read(in)
}
}
然后以下失敗:
val hs = hookSer[Transport](transportSer)
<console>:15: error: type mismatch;
found : => Source[Transport] => Serializer[Transport]
required: Source[Transport] => Serializer[Transport]
val hs = hookSer[Transport](transportSer)
^
如何在不更改功能名稱參數的情況下(盡可能)解決此問題?
似乎可以寫出類型(=> Source[A]) => Serializer[A]
:
def hookSer[A](peerSelf: (=> Source[A]) => Serializer[A]) : Serializer[Hook[A]] = ...
val hs = hookSer[Transport](transportSer)
val h = hs.read(new In {})(new Tx {})
val t = h.source.get(new Tx {})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.