任何人都可以向我展示一个简单的groovy类型推断示例及其优势吗? 我已经阅读了很多文章和一本关于groovy的书,但是找不到一个简单的例子。
答案 0 :(得分:4)
我wrote an answer前一段时间的例子。检查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
}
答案 1 :(得分: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