代码之家  ›  专栏  ›  技术社区  ›  switch201

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

  •  -1
  • switch201  · 技术社区  · 7 年前

    也许没有办法,但我想我会问的。

    让我举例说明我的问题。将此想象为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 回复  |  直到 7 年前
        1
  •  1
  •   Ibrahim.H tim_yates    7 年前

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

    Map 使用替代语法:

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

    println myMap.example.Hello
    

    希望这有帮助。