Type Coercion is the conversion of one type of object to a new object of a different type with similar content. Tapestry frequently must coerce objects from one type to another. A common example is the coercion of a string into an integer or a double.
Although type coercions happen more inside tapestry-core (including coercions of component parameters), they may also happen inside tapestry-ioc, such as when injecting a value, rather than a service, into a builder method.
Like everything else in Tapestry, type coercions are extensible. At the root is the TypeCoercer service. Its configuration consists of a number of CoercionTuples. Each tuple defines how to coerce from one type to another. The initial set of coercions is focused primarily on coercions between different numeric types:
Default Type Coercions
There are a few special coercions related to
List wraps a lone object as a singleton list, we then need
List to ensure that
null (rather than a singleton list whose lone element is a
Tapestry can interpolate necessary coercions. For example, say it is necessary to coerce a
StringBuffer to an
Integer; the TypeCoercer service will chain together a series of coercions:
Coercing from null
null is special; it is not a spanning search as with the other types. Either there is a specific coercion from
null to the desired type, or no coercion takes places (and the coerced value is
The only built-in
null coercion is from
boolean (which is always false).
List of Coercions
As of Tapestry versions 5.1 and 5.2, the following coercions are available:
Contributing New Coercions
TypeCoercer is extensible; you may add new coercions as desired. For example, let's say you have a
Money type that represents an amount of some currency, and you want to be able to convert from
Money. Further, let's assume that
Money has a constructor that accepts a
BigDecimal as its parameter. We'll use a little Tapestry IOC configuration jujitsu to inform the TypeCoercer about this coercion.
Further, since TypeCoercer knows how to convert
BigDecimal, or even
BigDecimal, all of those coercions would work as well.
When creating a coercion from
Void.class as the source type. For example, the built-in coercion from
Boolean is implemented as: