Thread overview
HOW? To Object variable assignment.
Jul 13, 2004
Blandger
Jul 13, 2004
Thomas Kuehne
Jul 13, 2004
Arcane Jill
July 13, 2004
Porting java code I incidentally stuck with such an easy and stupid problem.

Java uses Object variable as 'universal type' for storing 'everything
(although it's not a typesafe).
How legally to assign variable value of some type to the Object variable in
D?

Something like on java:
-------------
 Object [] table = new Object[n];
 String key = "some key";
 table [0] = key; // legal code
...
and vice versa
------------

But for D I stuck:
...
   Object[] obj = new Object[10];
   wchar[] str = "fff";
   obj[0] = cast(Object)str; // error: cannot cast from wchar[] to Object

What's I make wrong?



July 13, 2004
Blandger wrote:

> Something like on java:
> -------------
>  Object [] table = new Object[n];
>  String key = "some key";
>  table [0] = key; // legal code
> ...
> and vice versa
> ------------
> 
> But for D I stuck:
> ...
>    Object[] obj = new Object[10];
>    wchar[] str = "fff";
>    obj[0] = cast(Object)str; // error: cannot cast from wchar[] to Object
> 
> What's I make wrong?

It's like trying the following in Java:
Object o   = new Object();
int i  = 1;
o = (Object)i;


You have to use "wrapper" classes similar to java.lang.String and java.lang.reflect.Array.

Thomas
July 13, 2004
In article <cd1ahm$170b$2@digitaldaemon.com>, Blandger says...

>   Object[] obj = new Object[10];
>   wchar[] str = "fff";
>   obj[0] = cast(Object)str; // error: cannot cast from wchar[] to Object
>
>What's I make wrong?

That's not built into D like it is in Java. But you can do the same thing by hand, like this:

#    class ObjectWrapper(T) // template class
#    {
#        T a;
#        this(T x) { a = x; }
#    }

Then you can do

#    obj[0] = new ObjectWrapper!(wchar[])(str);

(And of course there's always the old type-unsafe C fallback of void*).
Arcane Jill