Archive

Posts Tagged ‘asType’

Groovy 2 asType conversation

August 13, 2014 Leave a comment

Groovy enables you to provide overload a method “asType (Class clazz)”. However i had some difficulty with this relating to duck typing which didn’t work. Not entirely sure why.

i’d been trying to use a grails app with joda date – LocalDate, and new java8 LocalDate. however the java8 version kept crashing when i ran a test – so i dropped back to java 7 and Joda package.

Hibernate doesn’t seem to handle Joda/Java LocalDates (havn’t tried this very far). So i kept it simple i created a Birthday Domain Class with three int params (year, month,date) and wanted to ensure i could generate a LocalDate from this.

first attempt was try this using duck typing

	Object asType (clazz) {
		if (clazz == LocalDate) {
			new LocalDate (year, month, day)
		}
		else {
			super.asType(clazz)
		}

	}

however this wouldn’t fire when i tried

def bday = new Birthday (year:1962, month:10, day:20) as LocalDate

and it said it couldn’t handle the caste at runtime – odd.

eventually tried and explicitly set the type for the method and then it ran successfully and did the dynamic caste

	Object asType (<strong>Class</strong> clazz) {
		if (clazz == LocalDate) {
			new LocalDate (year, month, day)
		}
		else {
			super.asType(clazz)
		}

	}

adding the explicit type did it

Advertisements
Categories: Grails, Groovy Tags:
%d bloggers like this: