Question

In the following scenario, by-name parameters cause conflict with functions.

Given some serialization infrastructure:

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 }

And an example type along with its serializer:

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

Now imagine a wrapper called Hook which deals with the recursive/mutual connectivity:

trait Hook[A] {
   def source: Source[A]
}

And its serializer:

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

Then the following fails:

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)
                                      ^

How can this be fixed without changing by-name parameters to functions (as far as possible)?

Was it helpful?

Solution

It seems one can write the type (=> 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 {})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top