Create a method that receives a type parameter but not as a parameter, just like classOf
I have the following code:
class ServletSpec extends Specification { def createServlet[T <: HttpServlet](clazz: Class[T]): T = { val instance = clazz.newInstance() instance.init() instance } }
That is called like this:
spec.createServlet( classOf[DocumentationServlet] )
How can I define this method so that I can call it like this:
spec.createServlet[DocumentationServlet]
Answers
Using Manifests:
class ServletSpec extends Specification { def createServlet[T <: HttpServlet]()(implicit manifest: Manifest[T]) = { val instance = manifest.erasure.newInstance().asInstanceOf[T] instance.init() instance } } new ServletSpec().createServlet[DocumentationServlet]()
The implicit parameter is filled in by the compiler, and a Manifest contains the type information required to create a new instance. For more information, see What is a Manifest in Scala and when do you need it?