Scala classOf for type parameter

后端 未结 2 1692
耶瑟儿~
耶瑟儿~ 2020-11-28 23:15

I am trying to create a generic method for object updates using scala / java but I can\'t get the class for a type parameter.

Here is my code:

object         


        
2条回答
  •  星月不相逢
    2020-11-29 00:01

    Vasil's and Maxim's answer helped me.

    Personally, I prefer the syntax where implicit is used for adding such parameters (the presented : ClassTag is shorthand for it. So here, in case someone else also sees this to be a better way:

    import scala.reflect.ClassTag
    
    object WorkUnitController extends Controller {
      def updateObject[T](toUpdate: T, body: JsonObject)(implicit tag: ClassTag[T]){
        val source = gson.fromJson(body, tag.runtimeClass)
        ???
      }
    }
    

    Disclaimer: I did not compile the above, but my own similar code works this way.

提交回复
热议问题