3

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]
Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158

1 Answers1

5

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?

Community
  • 1
  • 1
Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171