Peter Ren
Peter Ren

Reputation: 177

Scala typeclass without function argument

I'm currently working on my network library in scala. I encountered something like this:

object Packet {
  trait Reader[T] {
    def read(iterator: ByteIterator): T
  }

  object Reader {
    implicit object ByteReader extends Reader[Byte] {
      def read(iterator: ByteIterator): Boolean = iterator.getByte
    }
  }
}

class Packet {
  import Packet._

  def iterator: ByteIterator

  def read[T](implicit e: Reader[T]): T = {
    e.read[T]()
  }

  def readByte(): Byte = {
    this.read[Byte]()  // <- Unspecified value parameter e
  }
}

When I search the internet for answers, all of the examples I read was about function WITH arguments, not like me, my "read" function takes 0 argument. Is this the problem? How can I solve this?

I come from a C++ background, know the basic of Haskell, like the typeclass stuff. In C++, I can just do template specialization to make it work. In Haskell, (read :: Byte) will work. I tried to use reflection, but since packet read write is a very low level operation, reflection should be really bad for performance. Is there a way to make this work?

Upvotes: 0

Views: 144

Answers (1)

user1804599
user1804599

Reputation:

Prepend an empty parameter list:

def read[T]()(implicit e: Reader[T]): T =
  e.read(iterator)

def readByte(): Byte =
  this.read[Byte]()  // <- HURRAY IT WORKS

Removing the argument list (()) at the call site also works, but is typically frowned upon because syntactically argumentless calls are expected to be referentially transparent.

Upvotes: 1

Related Questions