How to create a generic Scala function that returns an object based on a generic type?

(Scala initial question)

I am trying to write a program in Scala that performs a series of checks of source files in C ++, and I want to implement optional audit logging.

The following works fine for one check:

val headerFiles = files.filter(_.matches(".*?\\.h$")) val headerGuardChecker = if(options.contains('verbose)) { new HeaderGuard with LoggingFileCheckerTrait } else { new HeaderGuard } headerFiles.foreach(h => if (! headerGuardChecker.check(new File(h))) println(h + " doesn't have a header guard")) 

however, when I try to generalize this with generics:

  def checker[T] = if(options.contains('verbose)) { new T with LoggingFileCheckerTrait } else { new T } val headerFiles = files.filter(_.matches(".*?\\.h$")) headerFiles.foreach(h => if (! checker[HeaderGuard].check(new File(h))) println(h + " doesn't have a header guard")) 

I get compilation errors for two new statements, claiming that T is not a type. I believe this is caused by type erasure, but I have not found a way around this. Is there a way to do what I want to do?

+7
source share
1 answer

Take a look at the Scala manifestos. They often allow you to bypass erasing styles on the JVM.

 scala> def instantiate[T](implicit m:Manifest[T]) = m.erasure.newInstance().asInstanceOf[T] instantiate: [T](implicit m: Manifest[T])T scala> instantiate[String] res0: String = "" 

Here's a good introduction for showing up in Scala

+7
source