-1

I am having a list of string as follows.

List l = ["1","2","3"]

And I have a class like as follows.

class person {
    String name
}

I want to create a list of person object from List l.

I have tried using groovy list collect but I am not able to do so.

Here is my code.

class testJsonSlurper {
    static void main(String[] args) {
        List l = ["1","2","3"]
        def l2 = l.collect { new person(it) }
        println(l2)
    }
}

But I getting following error.

Exception in thread "main" groovy.lang.GroovyRuntimeException: Could not find matching constructor for: testJsonSlurper$person(java.lang.String)
Apoorva sahay
  • 1,640
  • 3
  • 23
  • 43

1 Answers1

2

In your class testJsonSlurper, you have to change this line

def l2 = l.collect { new person(it) }

into

def l2 = l.collect { new person(name:it) }

This is what we call Named argument constructor. You can find more about Named argument constructor here.

If you do not want to make this change, then you need to add constructor in class person yourself. The class person should look like this after adding constructor.

​class person {    
    String name

    person(name){
        this.name = name
    }
}
Ramsharan
  • 2,069
  • 2
  • 20
  • 25