如何在Groovy中“内联”类型转换

如何在Groovy中“内联”类型转换,groovy,Groovy,也许没有办法做到这一点,但我想我会问 让我用一个例子来解释我的问题。将其想象为groovy脚本: def myMap = [:] def myMap2 = ["Hello":'World'] myMap.put("example", myMap2) //now if I try to write this: myMap.get("example").get("Hello") //the get("Hello") comes up as an unrecognized method because

也许没有办法做到这一点,但我想我会问

让我用一个例子来解释我的问题。将其想象为groovy脚本:

def myMap = [:]
def myMap2 = ["Hello":'World']
myMap.put("example", myMap2)
//now if I try to write this:
myMap.get("example").get("Hello")
//the get("Hello") comes up as an unrecognized method because groovy doesn't know what type of object it is dealing with until run time
//To avoid this I can do this:
def x = (Map) myMap.get("example")
x.get("Hello")
我想知道是否有一种方法可以让我从myMap.get'example'中键入返回值,而不必生成新变量/新行


如果我正确理解了您的问题,那么这个问题与解析器语法和Groovy语言的动态行为的性质有关。我不认为这与IntelliJ有关,因为GGTS表现出相同的行为

因此,正如您所说,您可以使用其他语法访问Map:

println myMap["example"]["Hello"]
另一种可能的方法是使用对对象属性的直接访问:

println myMap.example.Hello

希望这有帮助。

你试过了吗?它现在可以按照您的需要工作:myMap.getexample.getHello返回世界。一旦你修正了语法错误,上面的例子对我也适用,正如@tim_yates所说的,你只需要修正第二行的语法,你也可以使用以下语法检索你的对象:println myMap[example][Hello]。@bitsnaps我想你们还不明白这个问题,因为我刚刚再试了一次。我不在乎代码返回什么,我修复了语法错误。代码运行正常,但myMap.getexample.getHello中的第二个get作为无法识别的变量出现。我再次理解代码将运行和执行良好。我只是想让它成为一个公认的变量。请看我的附件screenshot@tim_yates请看上面comment@bitsnaps我想你评论的第二部分就是我想要的答案,如果你想回答,我可以接受