具有构造函数的类型类

时间:2018-03-07 18:34:03

标签: scala typeclass

调用构造实现某些类型类的实例的函数的首选方法是什么?以下示例中为deserialize

// Simulacrum annotation
@typeclass trait Encodable[A] {
  def deserialize(bytes: Seq[Byte]): Try[A] // Constructor
  def serialize(proof: A): Seq[Byte]
}

// implementation Encodable for Int
implicit val IntEncodable: Encodable[Int] = new Encodable[Int] {
  def deserialize(bytes: Seq[Byte]): Try[Int] = Success(bytes.head)
  def serialize(value: Int): Seq[Byte] = List(value.toByte)
}

// import Simulacrum generated ops
import Encodable.ops._

// is it best practise to define a function like this for all constructor-like functions in the typeclass?
def deserialize[A:Encodable](bytes: Vector[Byte])(implicit instance: Encodable[A]): Try[A] = instance.deserialize(bytes)
// or def deserialize[A:Encodable](bytes: Vector[Byte]): Try[A] = Encodable[A].deserialize(bytes) 

// call constructor
val value: Int = deserialize(Vector(1)).get
// call method
println(value.serialize)

1 个答案:

答案 0 :(得分:1)

对我来说,这太过分了。我喜欢的方式,以及我在其他代码库中看到的只是:

val value: Int = Encodable[Int].deserialize(Vector(1)).get

我认为额外的deserialize方法并没有多大意义。我也看到了:

val value: Int = implicitly[Encodable[Int]].deserialize(Vector(1)).get

对于那些以前没有见过仿真的人来说可能更为熟悉,但我认为没必要。