Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I cannot use string methods inside groovy closure? – no candidate for method call

I have simple hashmap and want to manipulate it but IDE does not recognize the methods. Completely new to Groovy so not sure what is wrong.

    def percentages = [
        "x1" : "20%",
        "x2" : "30%",
        "x3" : "0.4",
        "x4" : "50%",
        "x5" : "0.6"]

    percentages.each {
    val ->
         if(val[2].endsWith("%")) {
        val[2].deleteCharAt(val.length()-1)
        println val
    }
}

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you do percentages.each you iterate over map and each element is java.util.Map.Entry. Here is probably what you need:

import java.util.Map.Entry

def percentages = [
    "x1": "20%",
    "x2": "30%",
    "x3": "0.4",
    "x4": "50%",
    "x5": "0.6"]

percentages.each { Entry<String, String> val ->
    if (val.value.endsWith("%")) {
        val.value = val.value.substring(0, val.value.length() - 1)
        println val
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading