Jay Taylor's notes

back to listing index

class - Why is the Manifest not available in the constructor? - Stack Overflow

[web search]
Original source (stackoverflow.com)
Tags: scala manifests stackoverflow.com
Clipped on: 2012-09-25

Consider this code:

class Foo[T : Manifest](val id: String = manifest[T].erasure.getName)

I basically want to store an identifier in Foo, which is often just the class name.

Subclass which do not need a special identifier could then easily use the default value.

But this doesn't even compile, the error message is:

error: No Manifest available for T.

Is there another approach which will work?


Why does this work if the manifest isn't available until the primary constructor?

class Foo[T: Manifest](val name: String) { 
def this() = this(manifest[T].erasure.getName)
asked Sep 3 '11 at 17:39
Image (Asset 1/2) alt= 8,5901688

94% accept rate
Not an answer, but you'll have much cleaner code if you use manifest[T] instead of implicitly[Manifest[T]]. – Kevin Wright Sep 4 '11 at 7:55
add comment

1 Answer

up vote 7 down vote accepted

When the syntactic sugar is removed from that context bound, it gets rewritten as:

class Foo[T]
(val id: String = implicitly[Manifest[T]].erasure.getName)
(implicit ev$1: Manifest[T]) = ...

So the Manifest evidence simply isn't available when determining the default value of id. I'd instead write something like this:

class Foo[T : Manifest](id0: String = "") {
val id = if (id0 != "") id0 else manifest[T].erasure.getName

In your second approach (which is a great solution, by the way!), expect a rewrite similar to:

class Foo[T](val name: String)(implicit x$1: Manifest[T]) { 
def this()(implicit ev$2: Manifest[T]) = this(manifest[T].erasure.getName)

So yes, the manifest is available before the call to manifest[T].erasure

answered Sep 3 '11 at 18:02
Image (Asset 2/2) alt= 21.7k12976
But doesn't create that a superfluous field? – soc Sep 3 '11 at 18:29
To avoid the superfluous field, remove the val modifier from the definition of id0? – Kipton Barros Sep 3 '11 at 18:34
Mhhh ... I think I just solve it by adding a – soc Sep 3 '11 at 18:35
Kipton - True that, consider it gone – Kevin Wright Sep 4 '11 at 7:51
@soc - It's usually best to avoid underscores, a heavily overloaded symbol, unless the spec demands it. – Kevin Wright Sep 4 '11 at 9:41
add comment

Your Answer

community wiki

Not the answer you're looking for? Browse other questions tagged or ask your own question.