What kind of type coercion does groovy support? I saw map coercion and closure coercion. Are there any other?
And what is the difference between type coercion and type inference? For example
def i = 1000 // type infere to Integer
i = 1000000000000 // type infere to Long or is this type coercion?
Groovy can use dynamic untyped variables whose types are assigned at runtime. Type inference refers to the automatic deduction of the type of an expression.
In your example: def i = 1000
assigns an instance of java.lang.Integer to the variable
Few simple tests as examples:
assert "Integer" == 1000.class.simpleName
assert "Long" == 1000000000000.class.simpleName
assert "BigDecimal" == 3.14159.class.simpleName
assert "Float" == 3.14159f.class.simpleName
According to Groovy's documentation: "Closures in Groovy work similar to a "method pointer", enabling code to be written and run in a later point in time".
Also, when working on Collections of a determined type, the closure passed to an operation on the type of collection can be inferred.
Type coercion is in play when passing variables to method of different type or comparing variables of different types. In comparing numbers of different types the type coercion rules apply to convert numbers to the largest numeric type before the comparison. So the following is valid in Groovy.
Byte a = 12
Double b = 10
assert a instanceof Byte
assert b instanceof Double
assert a > b
The Groovy "as" keyword is used in following situations:
In addition to type coercion in maps and closures, there is also "Groovy Truth", which evaluates a type in an expression as TRUE or FALSE.
References:
Static Groovy and Concurrency: Type Inference in Action
http://groovy.dzone.com/articles/static-groovy-and-concurrency-3
Groovy Operator Overloading
http://groovy.codehaus.org/Operator+Overloading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With