Skip to content

faq 19431446

Billy Charlton edited this page Sep 5, 2018 · 2 revisions

How to convert typed Id?

by Michael Zilske on 2014-09-30 08:42:34


Kai asks:

How do you convert typed Ids? I could get the following piece of code to compile:

	@SuppressWarnings({ "cast", "unchecked", "rawtypes" })
 	private static Id<Vehicle> createVehicleIdFrom( Id<Person> id ) {
 		return (Id<Vehicle>) (Id) id ; // weird.
 	}
 

Is that how it goes? I find in particular weird that I first need to convert Id<Person> to the untyped Id and only then to the newly typed Id<Vehicle; is that how it has to go? Thanks ...

Presumably better for this particular situation:

	private static Id<Vehicle> createVehicleIdFrom( Id<Person> id ) {
 		return Id.create(id.toString(), Vehicle.class) ;
 	}
 

??


Comments: 1


Re: How to convert typed Id?

by Michael Zilske on 2014-09-30 08:44:01

Marcel answers:

Id.create(personId, Vehicle.class)


One should create a new Id with the correct type. The Id class has a create method that accepts such an other Id.

Reasoning for creating a new Id instead of casting: While it could be casted due to the generics being stripped away at compile time, the new Id implementation maintains a cache for Ids per type. Casting an Id circumvents that cache. So:

Id<Person> id1 = Id.create("1", Person.class);
 Id<Person> id2 = Id.create("1", Person.class);
 

the two lines above will actually return the same object twice, thus id1 == id2 is true.
By casting, this would no longer be true, which might lead to strange errors later (e.g. objects not being found in a Map).

Clone this wiki locally