Mismatch between call-by-name parameter and function type

174 views Asked by At

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

1

There are 1 answers

0
0__ On BEST ANSWER

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