How to get ClassTag form TypeTag, or both at same time?

前端 未结 2 753
遥遥无期
遥遥无期 2020-11-29 11:48

I have some code like this:

class ReflectiveJsonFormat[T:TypeTag] extends JsonFormat[T] {
  def write(x: T) : JsValue = {
   val t = typeOf[T]
   val getters         


        
相关标签:
2条回答
  • 2020-11-29 12:26

    Well scala does support multiple context bounds if that is what you are after:

    class ReflectiveJsonFormat[T:TypeTag:ClassTag] 
    
    0 讨论(0)
  • 2020-11-29 12:45

    The library doesn't provide a built-in method that directly converts a TypeTag to a ClassTag, but you can write one:

    import reflect.runtime.universe._
    import reflect.ClassTag
    
    def typeToClassTag[T: TypeTag]: ClassTag[T] = {
      ClassTag[T]( typeTag[T].mirror.runtimeClass( typeTag[T].tpe ) )
    }
    

    Then in your method just add before the implicit ClassTag is needed:

    implicit val c = typeToClassTag[T]
    
    0 讨论(0)
提交回复
热议问题