Question

Can anyone show me a simple example for type inference in groovy and the advantage of it? I read already many articles and a book about groovy but couln't find a simple example for this.

Was it helpful?

Solution 2

Is this simple enough to apprehend?

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

OTHER TIPS

I wrote an answer sometime ago with an example. Check that the animal() method return type is def, and it returns two objects of different types. It infers the common supertype of both.

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top