Reputation: 2879
What I'm trying to do (this is a simplified example, but contains all I need)
trait MyTrait[T] {
val name = Somefunction(simpleName)
def simpleName(implicit m:Manifest[T]) = m.erasure.getSimpleName
}
But I get a "No Manifest available for T" compiler error on the val initialisation at simpleName.
doing
val name = Somefunction(implicitly[Manifest[T]].erasure.getSimpleName)
does the same
Somefunction returns a object that is expensive to create, so I only want to create it once.
The only way I got this to work is by using a function that checks if the object has already been created and if so then just return it else create it first and then return it.
EDIT -- added example of how I can get it to work
example
trait MyTrait[T] {
var n:MyClass = null
def name(implicit m:Manifest[T]) = {
if(n == null) n = Somefunction(implicitly[Manifest[T]].erasure.getSimpleName)
n
}
}
Upvotes: 0
Views: 291
Reputation: 134270
You cannot declare the type parameter of a trait
as having a Manifest
context-bound because it is equivalent to requiring a constructor parameter (which a trait cannot have). I understand that allowing this is planned for some future version of scala.
Furthermore, a val
cannot have parameters, so it is simply not possible to instantiate a val
dependent on an instance of Manifest[T]
that I can see. But you have said you have got this to work: how?
Upvotes: 1