This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Manifest, implicits and apply

No replies
Roman Roelofsen
Joined: 2009-03-03,
User offline. Last seen 42 years 45 weeks ago.

Dear Scala Fellows!

In a Scala DSL, I want to be able to write

withClass [String]

and

withClass [String] {
// ...
}

I want avoid to write classOf[...] all the time. The first one is
quite easy to implement:

def withClass[A](implicit clazz: scala.reflect.Manifest[A])

However, I have some trouble solving the 2nd one. I tried the
following solutions, none of them worked:

(1) Overloading the withClass method

def withClass[A](implicit clazz: scala.reflect.Manifest[A])
def withClass[A](block: => Unit)(implicit clazz: scala.reflect.Manifest[A])

When calling without the block, the Scala compiler does not know it I
want to call the non-block method or if I want to partially apply the
with-block method.

(2) Returning an object with an apply method
class Helper {
def apply(block: => Unit) = {...}
}
def withClass[A](implicit clazz: scala.reflect.Manifest[A]) = {
new Helper
}

When I try to pass the block, the scala compiler thinks that I want to
pass the block as the scala.reflect.Manifest parameter. Directly
calling apply works:

withClass [String].apply {
// ...
}

What else can I do?

Cheers,

Roman

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland