Ruslan Mikhalev
Ruslan Mikhalev

Reputation: 1

Cast any Map to custom type

I'm trying to find a way to cast any Map to instance of my class A using "as" operator.in Groovy, like this:

import java.util.concurrent.ConcurrentHashMap;
class A { 
    def list = new ArrayList();
    A( Map map ) {
        for( e in map.entrySet() ) {
            list.add( e.getKey );
            list.add( e.getValue() );
        }
    }
};
def map = [ key1 : 'value1', key2 : 'value2' ] as ConcurrentHashMap;
def instA = map as A;
assert instA.list.containsAll( [ 'key1', 'value1', 'key2', 'value2' ] );

This is a hypothetical example, but it shows the essence of the problem.

Upvotes: 0

Views: 484

Answers (1)

tim_yates
tim_yates

Reputation: 171084

Once I fixed your typos in the question, (and replaced the for loop with a more groovy solution), this just seems to work:

import java.util.concurrent.ConcurrentHashMap;

class A { 
    def list
    A( Map map ) {
        list = map.inject([]) { l, key, value -> l << key << value }
    }
}

def map = [ key1 : 'value1', key2 : 'value2' ] as ConcurrentHashMap
def instA = map as A

assert instA.list == [ 'key1', 'value1', 'key2', 'value2' ]

Upvotes: 1

Related Questions