Anthony Berent
Anthony Berent

Reputation: 105

How do I create a generic Scala function that returns an object based on the generic type?

(Scala beginner question)

I am trying to write a program in Scala that does a number of checks on C++ source files, and I want to implement optional logging of checks.

The following works fine for a single 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 using 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 compile errors on the two new statements, claiming that T isn't a type. I believe this caused by type erasure, but I haven't found a way of working round this. Is there a way of doing what I want to do?

Upvotes: 7

Views: 337

Answers (1)

Adam Rabung
Adam Rabung

Reputation: 5224

Take a look at Scala "manifests". They often allow you to circumvent type erasure 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 intro for manifests in Scala

Upvotes: 7

Related Questions