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

时间:2018-09-10 21:18:38

标签: 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')的收益进行类型转换,而无需做出新的变量/换行

See how the second get is unrecognized

1 个答案:

答案 0 :(得分:1)

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

很好-正如您所说-您可以使用其他语法访问Map

println myMap["example"]["Hello"]

另一种可能的方法是直接访问对象的属性:

println myMap.example.Hello

希望获得帮助。