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

instantiating class from parameter

16 replies
Charles F. Munat
Joined: 2008-12-29,
User offline. Last seen 42 years 45 weeks ago.

I want to do something like this:

class Something[T] {
def getOne(): T {
// instantiate a new T here with default values
}
}

Is this possible? Maybe with this amazing new Manifest thingy? There
really doesn't seem to be a good text or tutorial covering this sort of
thing. Anyone know of one? Got a link?

TIA,

Chas.

H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: instantiating class from parameter

class Something[T](implicit val m:Manifest[T]) {
def getOne(): T { m.erasure.newInstance }
}

Am 13.09.2010 12:29, schrieb chas@munat.com:
> I want to do something like this:
>
> class Something[T] {
> def getOne(): T {
> // instantiate a new T here with default values
> }
> }
>
> Is this possible? Maybe with this amazing new Manifest thingy? There
> really doesn't seem to be a good text or tutorial covering this sort of
> thing. Anyone know of one? Got a link?
>
> TIA,
>
> Chas.
>
>

Lex
Joined: 2010-02-28,
User offline. Last seen 42 years 45 weeks ago.
Re: instantiating class from parameter
On Mon, Sep 13, 2010 at 7:31 AM, HamsterofDeath <h-star@gmx.de> wrote:


   class Something[T](implicit val m:Manifest[T]) {
     def getOne(): T { m.erasure.newInstance }
   }

 
This wont work unless T has a default no-argument constructor.
H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: instantiating class from parameter
i was expecting the question's author to be able to deduce how to continue from there

Am 13.09.2010 18:29, schrieb Lex:
AANLkTinEyjEps2hNU7DxcjUSiDLVPfSbLHXNTE4Xp82x [at] mail [dot] gmail [dot] com" type="cite"> On Mon, Sep 13, 2010 at 7:31 AM, HamsterofDeath <h-star [at] gmx [dot] de" rel="nofollow">h-star@gmx.de> wrote:


   class Something[T](implicit val m:Manifest[T]) {
     def getOne(): T { m.erasure.newInstance }
   }

 
This wont work unless T has a default no-argument constructor.

Philippe Lhoste
Joined: 2010-09-02,
User offline. Last seen 42 years 45 weeks ago.
Re: instantiating class from parameter

On 13/09/2010 18:29, Lex wrote:
> class Something[T](implicit val m:Manifest[T]) {
> def getOne(): T { m.erasure.newInstance }
> }
>
>
> This wont work unless T has a default no-argument constructor.

Actually, it doesn't work at all. At least with my naive tentative to test it with Scala
2.8.0.
I get:

Tests.scala:34: error: type mismatch;
found : _$1 where type _$1
required: T
def getOne(): T = { m.erasure.newInstance }
^
one error found

which is a quite cryptic error message for the newbie I am... :-)
Perhaps it is way above my league, but I was curious and interested.

I see Manifest is actually still undocumented in the official JavaDoc. (And, yes, I have
read the article of Jorge Ortiz.)

Randall R Schulz
Joined: 2008-12-16,
User offline. Last seen 1 year 29 weeks ago.
Re: Re: instantiating class from parameter

On Monday September 13 2010, Philippe Lhoste wrote:
> On 13/09/2010 18:29, Lex wrote:
> > class Something[T](implicit val m:Manifest[T]) {
> > def getOne(): T { m.erasure.newInstance }
> > }
> >
> >
> > This wont work unless T has a default no-argument constructor.
>
> Actually, it doesn't work at all. At least with my naive tentative to
> test it with Scala 2.8.0.
> I get:
>
> Tests.scala:34: error: type mismatch;
> found : _$1 where type _$1
> required: T
> def getOne(): T = { m.erasure.newInstance }
> ^
> one error found
>
> which is a quite cryptic error message for the newbie I am... :-)
> Perhaps it is way above my league, but I was curious and interested.

The static return type of newInstance is java.lang.Object, so you need
to cast it to T (plus you have to fix the syntax error):

class Something[T](implicit val m:Manifest[T]) {
def getOne(): T = { m.erasure.newInstance.asInstanceOf[T] }
}

The cast is guaranteed to succeed.

> I see Manifest is actually still undocumented in the official
> JavaDoc. (And, yes, I have read the article of Jorge Ortiz.)

Randall Schulz

H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: Re: instantiating class from parameter
you are right. i have no idea why my first suggestion does not compile. this one does: package x import javax.swing.JLabel /** * Developed with pleasure :)
* User: HoD
* Date: 30.08.2010
* Time: 19:04:07
*/ object Main { class Something[T](implicit val m: Manifest[T]) { def getOne() = {m.erasure.newInstance.asInstanceOf[T]} } def main(args: Array[String]) { new Something[JLabel]().getOne() } } Am 13.09.2010 19:04, schrieb Philippe Lhoste: > On 13/09/2010 18:29, Lex wrote: >> class Something[T](implicit val m:Manifest[T]) { >> def getOne(): T { m.erasure.newInstance } >> } >> >> >> This wont work unless T has a default no-argument constructor. > > Actually, it doesn't work at all. At least with my naive tentative to > test it with Scala 2.8.0. > I get: > > Tests.scala:34: error: type mismatch; > found : _$1 where type _$1 > required: T > def getOne(): T = { m.erasure.newInstance } > ^ > one error found > > which is a quite cryptic error message for the newbie I am... :-) > Perhaps it is way above my league, but I was curious and interested. > > I see Manifest is actually still undocumented in the official JavaDoc. > (And, yes, I have read the article of Jorge Ortiz.) >
Charles F. Munat
Joined: 2008-12-29,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: instantiating class from parameter

How nice to wake up, sit down at the computer, and find a difficult
problem so neatly solved. The question's author thanks you all.

Chas.

> On Monday September 13 2010, Philippe Lhoste wrote:
>> On 13/09/2010 18:29, Lex wrote:
>> > class Something[T](implicit val m:Manifest[T]) {
>> > def getOne(): T { m.erasure.newInstance }
>> > }
>> >
>> >
>> > This wont work unless T has a default no-argument constructor.
>>
>> Actually, it doesn't work at all. At least with my naive tentative to
>> test it with Scala 2.8.0.
>> I get:
>>
>> Tests.scala:34: error: type mismatch;
>> found : _$1 where type _$1
>> required: T
>> def getOne(): T = { m.erasure.newInstance }
>> ^
>> one error found
>>
>> which is a quite cryptic error message for the newbie I am... :-)
>> Perhaps it is way above my league, but I was curious and interested.
>
> The static return type of newInstance is java.lang.Object, so you need
> to cast it to T (plus you have to fix the syntax error):
>
> class Something[T](implicit val m:Manifest[T]) {
> def getOne(): T = { m.erasure.newInstance.asInstanceOf[T] }
> }
>
> The cast is guaranteed to succeed.
>
>
>> I see Manifest is actually still undocumented in the official
>> JavaDoc. (And, yes, I have read the article of Jorge Ortiz.)
>
>
> Randall Schulz
>

Charles F. Munat
Joined: 2008-12-29,
User offline. Last seen 42 years 45 weeks ago.
Re: Re: instantiating class from parameter

Would you happen to have a link to Jorge's article, Philippe?

Thanks!

Chas.

> On 13/09/2010 18:29, Lex wrote:
>> class Something[T](implicit val m:Manifest[T]) {
>> def getOne(): T { m.erasure.newInstance }
>> }
>>
>>
>> This wont work unless T has a default no-argument constructor.
>
> Actually, it doesn't work at all. At least with my naive tentative to test
> it with Scala
> 2.8.0.
> I get:
>
> Tests.scala:34: error: type mismatch;
> found : _$1 where type _$1
> required: T
> def getOne(): T = { m.erasure.newInstance }
> ^
> one error found
>
> which is a quite cryptic error message for the newbie I am... :-)
> Perhaps it is way above my league, but I was curious and interested.
>
> I see Manifest is actually still undocumented in the official JavaDoc.
> (And, yes, I have
> read the article of Jorge Ortiz.)
>
> --
> Philippe Lhoste

Gruntz Dominik
Joined: 2010-09-13,
User offline. Last seen 42 years 45 weeks ago.
Newbie question regarding Actor.react

Simple newbie question related to the Actor library:

The following code
def main(args: Array[String]){
Actor.self ! 1
Actor.receive {
case x : Int => println(x)
}
}
works fine and prints 1 (as expected).

However, if I replace actor.receive by Actor.react, a ClassCastException is thrown:
Exception in thread "main" java.lang.ClassCastException:
java.lang.Thread cannot be cast to scala.concurrent.forkjoin.ForkJoinWorkerThread

Why?

Thanks,
Dominik

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Newbie question regarding Actor.react

On Mon, Sep 13, 2010 at 11:46:33PM +0200, Gruntz Dominik wrote:
> However, if I replace actor.receive by Actor.react, a ClassCastException is thrown:
> Exception in thread "main" java.lang.ClassCastException:
> java.lang.Thread cannot be cast to scala.concurrent.forkjoin.ForkJoinWorkerThread
>
> Why?

That depends on the definition of "why". An overly reductionist answer
can be found in the comment where the CCE happens:

/**
* Arranges to asynchronously execute this task. While it is not
* necessarily enforced, it is a usage error to fork a task more
* than once unless it has completed and been reinitialized. This
* method may be invoked only from within ForkJoinTask
* computations. Attempts to invoke in other contexts result in
* exceptions or errors possibly including ClassCastException.
*/

Well, we can't say they didn't warn us. I don't know the actors lib
very well but I will just say I hope it's a bug, because it wouldn't
seem fair if the code you posted CCE-ed by design. Even if it's
incorrect for some reason, it can't be that incorrect.

Stephen Tu
Joined: 2010-02-24,
User offline. Last seen 42 years 45 weeks ago.
Re: Newbie question regarding Actor.react
Gruntz,

you can't use the lightweight react when using the thread proxy actor (which is what you get when you call actor.self not within an actor). this is probably more of what you want:

def main(args: Array[String]) {
  import scala.actors._
  import Actor._
  val a = actor {
    react {
      case e => println(e)
    }
   }
  a ! 1
}

On Mon, Sep 13, 2010 at 2:58 PM, Paul Phillips <paulp@improving.org> wrote:
On Mon, Sep 13, 2010 at 11:46:33PM +0200, Gruntz Dominik wrote:
> However, if I replace actor.receive by Actor.react, a ClassCastException is thrown:
>       Exception in thread "main" java.lang.ClassCastException:
>       java.lang.Thread cannot be cast to scala.concurrent.forkjoin.ForkJoinWorkerThread
>
> Why?

That depends on the definition of "why".  An overly reductionist answer
can be found in the comment where the CCE happens:

/**
 * Arranges to asynchronously execute this task.  While it is not
 * necessarily enforced, it is a usage error to fork a task more
 * than once unless it has completed and been reinitialized.  This
 * method may be invoked only from within ForkJoinTask
 * computations. Attempts to invoke in other contexts result in
 * exceptions or errors possibly including ClassCastException.
 */

Well, we can't say they didn't warn us.  I don't know the actors lib
very well but I will just say I hope it's a bug, because it wouldn't
seem fair if the code you posted CCE-ed by design.  Even if it's
incorrect for some reason, it can't be that incorrect.

--
Paul Phillips      | Eschew mastication.
Vivid              |
Empiricist         |
slap pi uphill!    |----------* http://www.improving.org/paulp/ *----------

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Newbie question regarding Actor.react

On Mon, Sep 13, 2010 at 03:32:41PM -0700, Stephen Tu wrote:
> you can't use the lightweight react when using the thread proxy actor
> (which is what you get when you call actor.self not within an actor).

Do you have some insight into why this requirement is enforced via a CCE
appearing at runtime? I freely admit my naivete, but from first
principles one would imagine there must be some other way to accomplish
it. I'd think it'd be better to crash the compiler or jettison the
machine out pod bay four than to quietly generate a CCE-in-waiting.

Stephen Tu
Joined: 2010-02-24,
User offline. Last seen 42 years 45 weeks ago.
Re: Newbie question regarding Actor.react
On Mon, Sep 13, 2010 at 5:38 PM, Paul Phillips <paulp@improving.org> wrote:
Do you have some insight into why this requirement is enforced via a CCE
appearing at runtime? I freely admit my naivete, but from first
principles one would imagine there must be some other way to accomplish
it.  I'd think it'd be better to crash the compiler or jettison the
machine out pod bay four than to quietly generate a CCE-in-waiting.

is there a means for enforcing this at compile time? how can one specify that a method be called only within a certain context (ie only from a forkjoin worker thread) statically? i think for the actor DSL to be of any actual use, there have to be a few methods which can possibly fail at runtime, like react. while i agree this is not an ideal error message,  fundametally the error will manifest itself at runtime.


  
extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Newbie question regarding Actor.react

On Mon, Sep 13, 2010 at 07:53:11PM -0700, Stephen Tu wrote:
> is there a means for enforcing this at compile time? how can one
> specify that a method be called only within a certain context (ie only
> from a forkjoin worker thread) statically?

I'm not sure it has to be enforced statically from wire to wire. There
are plenty of low-tech mechanisms. Let's see, here's a method from
elsewhere in trunk:

def executeAndWait[R, Tp](fjtask: Task[R, Tp]) {
if (currentThread.isInstanceOf[ForkJoinWorkerThread]) {
fjtask.fork
} else {
forkJoinPool.execute(fjtask)
}
fjtask.join
}

> i think for the actor DSL to be of any actual use, there have to be a
> few methods which can possibly fail at runtime, like react. while i
> agree this is not an ideal error message, fundametally the error will
> manifest itself at runtime.

Maybe I wasn't clear. In the languages we're working with here, all
programs have behaviors which you cannot know until runtime. That
doesn't mean we punt on channelling them somewhere useful. A CCE is
like blasting shrapnel through the side of the bus. You can do that,
but it's OK to politely signal to the driver that they should pull over.
The bus people will distinguish between these outcomes even if to us it
seems like one stop is as good as another.

Philippe Lhoste
Joined: 2010-09-02,
User offline. Last seen 42 years 45 weeks ago.
Re: instantiating class from parameter

On 13/09/2010 19:37, Randall R Schulz wrote:
> The static return type of newInstance is java.lang.Object, so you need
> to cast it to T (plus you have to fix the syntax error):
>
> class Something[T](implicit val m:Manifest[T]) {
> def getOne(): T = { m.erasure.newInstance.asInstanceOf[T] }

I should have guessed... Actually, I was suspecting it was such problem but I was confused
by the error message ("_$1 where type _$1" doesn't make sense, or it is a bug in the
compiler?).

Thanks for the heads up!
Works, for example, with:

val some = new Something[Random]
val someRandom = some.getOne
println(someRandom.nextInt(5))

Philippe Lhoste
Joined: 2010-09-02,
User offline. Last seen 42 years 45 weeks ago.
Re: instantiating class from parameter

On 13/09/2010 22:03, chas@munat.com wrote:
> Would you happen to have a link to Jorge's article, Philippe?

Manifests: Reified Types
Also mentioned in another interesting article:
Scala Manifests FTW

Still have to digest/assimilate them... :-)

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