Deaddorks
Deaddorks

Reputation: 71

Can scala implicitly join 2 implicits into an implicit tuple?

Context:
I am trying to work with Java's RandomAccessFile, and I want to be able to read/write anything with an implicit fixedBytable:

case class FixedBytable[T](private val size: Int,
                           private val read: ByteBuffer => T,
                           private val write: (T, ByteBuffer) => Unit)

I defined FixedBytable for all the basic byte/short/float/..., which works just fine. I was also able to define tuple_Bytable for all the tuple types, which can join 2 (or whatever sized tuple) FixedBytable into 1, that can read/write a tuple of the "children" (ex: FixedBytable[(Int, Int)].

Question:
Can you do this implicitly? Maybe I am phrasing this wrong, but is there a way to say that if you can implicitly find a FixedByable[A] and a FixedBytable[B], then you should know how to implicitly find a FixedBytable[(A, B)]?

Upvotes: 2

Views: 257

Answers (1)

Deaddorks
Deaddorks

Reputation: 71

Here is the solution to get my problem to work, hopefully you can abstract it away to whatever your situation is.
The key here is that you need both the implicit def, and an implicit at the start of the parameters.

/*
Note:
implicit def
implicit b1: ...
*/

implicit def tuple2Bytable[T1, T2](implicit b1: Bytable[T1], b2: Bytable[T2]): Bytable[(T1, T2)] =
  Bytable[(T1, T2)](
    b1.size + b2.size,
    bb => {
      val v1: T1 = b1.fromBytes(bb)
      val v2: T2 = b2.fromBytes(bb)
      (v1, v2)
    },
    (t, bb) => {
      b1.toBytes(t._1, bb)
      b2.toBytes(t._2, bb)
    }
  )

implicit def tuple3Bytable[T1, T2, T3](implicit b1: Bytable[T1], b2: Bytable[T2], b3: Bytable[T3]): Bytable[(T1, T2, T3)] =
  Bytable[(T1, T2, T3)](
    b1.size + b2.size + b3.size,
    bb => {
      val v1: T1 = b1.fromBytes(bb)
      val v2: T2 = b2.fromBytes(bb)
      val v3: T3 = b3.fromBytes(bb)
      (v1, v2, v3)
    },
    (t, bb) => {
      b1.toBytes(t._1, bb)
      b2.toBytes(t._2, bb)
      b3.toBytes(t._3, bb)
    }
  )

Upvotes: 2

Related Questions