1

任何人都可以向我展示一个简单的 groovy 类型推断示例及其优势吗?我已经阅读了很多关于 groovy 的文章和一本书,但找不到一个简单的例子。

4

2 回答 2

4

前段时间我用一个例子写了一个答案。检查animal()方法返回类型是否为def,它返回两个不同类型的对象。它推断出两者的共同超类型。

import groovy.transform.CompileStatic

@CompileStatic
class Cases {
  static main(args) {
    def bat = new Cases().animal "bat"

    assert bat.name == "bat" // Works fine

    assert bat.favoriteBloodType == "A+" // Won't compile with error 
                                         // "No such property: favoriteBloodType
                                         // for class: Animal"
  }

  def animal(animalType) {
    if (animalType == "bat") {
      new Bat(name: "bat", favoriteBloodType: "A+")
    } else {
      new Chicken(name: "chicken", weight: 3.4)
    }
  }
}

abstract class Animal {
  String name
}

class Bat extends Animal {
  String favoriteBloodType
}

class Chicken extends Animal {
  BigDecimal weight
}
于 2013-11-05T19:44:18.547 回答
2

这个简单到可以理解吗?

def doSomething(a, b){
   a + b
}

//Type inferred to String
assert "HelloWorld" == doSomething('Hello','World')
assert "String" == doSomething('Hello','World').class.simpleName

//Type inferred to Integer
assert 5 == doSomething(2,3)
assert "Integer" == doSomething(2,3).class.simpleName

//Type inferred to BigDecimal
assert 6.5 == doSomething(2.7,3.8)
assert "BigDecimal" == doSomething(2.7,3.8).class.simpleName

//Type inferred to Double
assert 6.5d == doSomething(2.7d,3.8d)
assert "Double" == doSomething(2.7d,3.8d).class.simpleName
于 2013-11-05T19:06:01.333 回答