OEurix
OEurix

Reputation: 433

Could I create a list of object in this way?

Now I have a class TransactGetItem:

public class TransactGetItem {

    private String table;

    /**
     * The primary key of the DynamoDB item. The map entry key is the name of the attribute,
     * and the map entry value is the value of the attribute.
     *
     * Required.
     */
    private Map<String, TypedValue> key;
}

I want to create a list of TransactGetItem in Groovy using:

List<TransactGetItem> items = [[[table: 'post'], [key: ['id': TypedValue.ofS('1')]]],
     [[table: 'author'], [key: ['id': TypedValue.ofS('1')]]],
     [[table: 'post'], [key: ['id': TypedValue.ofS('3')]]],
     [[table: 'genre'], [key: ['id': TypedValue.ofS('4')]]]]

Is this a correct way to do this? If is not, what is the correct way? If is, is there a more readable way to do it?

Upvotes: 0

Views: 55

Answers (1)

Daniel
Daniel

Reputation: 3370

That is not the correct way to do it; you are expecting Groovy to do type conversion that it simply does not know how to do.

Instead, consider instantiating items as shown here. Note that I changed your key type because I did not have TypedValue in my sandbox environment but the concept is certainly the same:

class TransactGetItem {
  private String table
  private Map<String, Integer> key

  // for convenience
  public String toString() {
    return "${table} -> ${key}"
  }
}

// this builds your list and adds the new items to it
List< TransactGetItem > items = [
  [table: 'post', key: [id: 1]],
  [table: 'author', key: [id: 1]],
  [table: 'post', key: [id: 3]],
  [table: 'genre', key: [id: 4]],
].collect{
  new TransactGetItem(it)
}

// this is just showing what they are and that they were added as the right class
items.each { 
  println it
  println it.getClass()
  println "---"
}

Result of the printout will be:

post -> [id:1]
class TransactGetItem
---
author -> [id:1]
class TransactGetItem
---
post -> [id:3]
class TransactGetItem
---
genre -> [id:4]
class TransactGetItem
---

Upvotes: 2

Related Questions