mericano1
mericano1

Reputation: 2913

Scala classOf for type parameter

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 WorkUnitController extends Controller {     
 def updateObject[T](toUpdate: T, body: JsonObject){
  val source = gson.fromJson(body, classOf[T]);
  ...
 }
}

The error i get is

class type required but T found

I know in java you can't do it but is this possible in scala at all?

Thanks!

Upvotes: 84

Views: 27920

Answers (2)

akauppi
akauppi

Reputation: 18076

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)
    ???
  }
}

Demonstration: https://scastie.scala-lang.org/Vij5rpHNRDCPPG1WHo566g

Upvotes: 10

Vasil Remeniuk
Vasil Remeniuk

Reputation: 20627

Due Manifest is deprecated (Since Scala 2.10.0) this is the updated answer -

import scala.reflect.ClassTag
import scala.reflect._

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

You should use ClassTag instead of ClassManifest and .runtimeClass instead of .erasure

Original answer - Yes, you can do that using manifests:

object WorkUnitController extends Controller {     
 def updateObject[T: ClassManifest](toUpdate: T, body: JsonObject){
  val source = gson.fromJson(body, classManifest[T].erasure);
  ...
 }
}

Upvotes: 99

Related Questions