无法在Groovy闭包中使用字符串方法 – 没有适用的方法调用候选者。

huangapple go评论66阅读模式
英文:

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 { key, val ->
    if (val.endsWith("%")) {
        val = val[0..-2]
        println val
    }
}
英文:

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
    }
}

无法在Groovy闭包中使用字符串方法 – 没有适用的方法调用候选者。

答案1

得分: 1

When you do percentages.each, you iterate over the map, and each element is of type 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
    }
}

or even more compact, as @daggett suggested:

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

percentages.each { k, v ->
    if (v.endsWith("%")) {
        percentages[k] = v.substring(0, v.length() - 1)
        println percentages[k]
    }
}
英文:

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 = [
    &quot;x1&quot;: &quot;20%&quot;,
    &quot;x2&quot;: &quot;30%&quot;,
    &quot;x3&quot;: &quot;0.4&quot;,
    &quot;x4&quot;: &quot;50%&quot;,
    &quot;x5&quot;: &quot;0.6&quot;]

percentages.each { Entry&lt;String, String&gt; val -&gt;
    if (val.value.endsWith(&quot;%&quot;)) {
        val.value = val.value.substring(0, val.value.length() - 1)
        println val
    }
}

or even more compact, as @daggett suggested:

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

percentages.each {k, v -&gt;
    if (v.endsWith(&quot;%&quot;)) {
        percentages[k] = v.substring(0, v.length() - 1)
        println percentages[k]
    }
}

huangapple
  • 本文由 发表于 2023年5月6日 20:22:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定