back to listing index

Scala classOf for type parameter - Stack Overflow

[web search]
Original source (stackoverflow.com)
Tags: scala manifests classOf
Clipped on: 2012-09-25

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!

asked Jun 1 '11 at 11:14
Image (Asset 1/2) alt= 1,029315

75% accept rate
  upvote
 flag
Ha ha. I hit the exact same use case. Literally word for word – Bryan Hunt Jun 15 at 9:20
add comment

1 Answer

up vote 21 down vote accepted

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);
 
...
 
}
}
answered Jun 1 '11 at 11:19
Image (Asset 2/2) alt= 9,84412356
  upvote
 flag
great thanks a million! – mericano1 Jun 1 '11 at 11:21
  upvote
 flag
Oh god that's amazing! I wish I'd known about this earlier! – Darkzaelus Jun 1 '11 at 11:22
1 upvote
 flag
You can even write manifest[T] instead of implicitly[Manifest[T]]. – Jean-Philippe Pellet Jun 1 '11 at 11:31
1 upvote
 flag
@mericano1 they've become an essential part of the language, and, I think, Manifests are no longer an experimental feature – Vasil Remeniuk Jun 1 '11 at 11:37
1 upvote
 flag
@mericano1 One update: Manifest and ClassManifest are now deprecated, having been replaced with TypeTag and ClassTag, respectively, on Scala 2.10. – Daniel C. Sobral Jun 15 at 13:48
add / show 8 more comments

Your Answer

 
community wiki

Not the answer you're looking for? Browse other questions tagged or ask your own question.