- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Manifest as factory
Fri, 2009-02-06, 16:50
Since scala.reflect.Manifest is not well documented, I don't know if
the next snippet is valid:
class Tax(val value: Int)
def createValue[A](implicit a: Manifest[A]{ def create(value: Int): A}) =
a.create(12)
println("value is " + createValue[Tax].value)
My intention is to instantiate the generic class A in a typesafe way,
without Manifest.erasure and reflection. Is Manifest capable to map
constructors?
If it is not currently possible, I think it's a nice issue to future releases.
Regards.
- Andrés
Fri, 2009-02-06, 18:17
#2
Re: Manifest as factory
Hi Andrés,
Andrés Testi wrote:
> Since scala.reflect.Manifest is not well documented, I don't know if
> the next snippet is valid:
>
> class Tax(val value: Int)
>
> def createValue[A](implicit a: Manifest[A]{ def create(value: Int): A}) =
> a.create(12)
It's valid, except that a.create doesn't exist (and you've missed a
closing bracket)...
> My intention is to instantiate the generic class A in a typesafe way,
> without Manifest.erasure and reflection. Is Manifest capable to map
> constructors?
I don't think this is going to be possible per se. There are other ways
to do similar things, such as using the typeclass pattern, but not so
generally or concisely. If you're interested I'll post an example.
Cheers,
Jon
There are two perspectives on questions of the form "Is this thing to do with manifests valid?".
a) Does it work?
b) No
Manifests are not "not well documented". They are an unspecified experimental feature which is incomplete and still undergoing development. No guarantees are made as to their functionality or future compatibility. Therefore depending on one's philosophical stance, either validity is determined by whether something works or all code written against them is invalid due to depending on unspecified implementation details.
That being said...
I don't see how this can reasonably work without changes to the type system. There's currently no way to parameterise a type as requiring a particular constructor. In particular your code as currently written has type safety equivalent to a.erasure.newInstance(12) because there is no sort of constraint on A.