Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type coercion in groovy

Tags:

groovy

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?
like image 985
Cengiz Avatar asked Oct 03 '22 12:10

Cengiz


1 Answers

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:

  • used for "Groovy" casting to convert of value of one type to another
  • used to coerce a closure into an implementation of single method interface
  • used to coerce a Map into an implementation of an interface, abstract, and/or concrete class

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.

  • null is false
  • empty String, Map, or Collection is false
  • Zero number is false
  • if ( list ); if ( string ), if ( map ) same as writing if (list != null && !list.isEmpty()) ...

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

like image 92
CodeMonkey Avatar answered Oct 13 '22 11:10

CodeMonkey