我正在尝试使用隐式来尝试覆盖我在 ADT 的案例类中拥有的序列化方法,但是我无法理解应该如何完成它
// START OF API//
/**
* Serialize methods defined here
*
*/
object Serializer {
def string(block: (String => String)) = block
def int(block:(Int => String)) = block
def double(block:(Double => String)) = block
}
/**
* These are the DEFAULT serializers
*/
object Implicits {
implicit val string = Serializer.string (s => s)
implicit val int = Serializer.int (i => i.toString)
implicit val double = Serializer.double (d => String.valueOf(d))
}
/**
*
* Our simple ADT defined here
*/
import Implicits._
abstract class Vehicle {
def serialize:String
}
case class Car(s:String) extends Vehicle {
def serialize: String = string(s)
}
case class Truck(i:Int) extends Vehicle {
def serialize: String = int(i)
}
case class RocketShip(d:Double) extends Vehicle {
def serialize: String = double(d)
}
// END OF API
// START OF USER CODE
object UserImplicit {
implicit val string = Serializer.string(s => s.capitalize)
}
object Main extends App{
val v = Car("some car")
println(v.serialize)
import test.UserImplicit._
// This SHOULD print a capatilized version i.e. SOME CAR
println(v.serialize)
}
// END OF USER CODE
基本上我想修补默认的序列化器方法(包含在里面的那些object Implicits
),以便 API 的用户可以实现自己的序列化器
我尝试了许多组合(例如在 atrait
而不是 a中使用隐含object
)但是我实际上并没有设法让它工作