Reputation: 20231
I have a enum defined like this
enum PropertyType { apartment, villa, plot }
enum PossesionType { readyToMove, underConstruction }
I am trying to create a generic method,which returns me the right enum when given a string as input
class Property<T> {
T getGenericType(String text) {
switch (text) {
case 'Ready to move':
return PossesionType.readyToMove;
break;
case 'Apartment':
return PropertyType.apartment;
break;
....
....
....
default:
return PossesionType.readyToMove;
}
}
I understand this will throw an error since it expects a return type of T, to get this working without generics I need to write two different functions with a different return type but both functions will basically do the same thing.
PropertyType getSelectedProperty(String text) {
switch (text) {
case 'Apartment':
return PropertyType.apartment;
break;
case 'Villa':
return PropertyType.villa;
break;
case 'Plot':
return PropertyType.plot;
break;
default:
return PropertyType.apartment;
}
}
PossesionType getSelectedPossession(String text) {
switch (text) {
case 'Ready to move':
return PossesionType.readyToMove;
break;
case 'Under Construction':
return PossesionType.underConstruction;
break;
default:
return PossesionType.readyToMove;
}
}
I am new to generics so can someone help me understand how can I achieve this.
Upvotes: 1
Views: 5184
Reputation: 71653
You need to write two different functions.
When calling a generic function, like T parseProperty<T>(String text) { ... }
, you need to know which type to return at compile time. Otherwise you'll have to pass dynamic
as type argument.
As you have also noticed, simply abstracting over the return type makes it hard to implement the function. You'll have to put as T
on every return expression, because there is no way to invent an object of an unknown type.
All in all, you are better off having either two functions, if you know the type at compile-time, or having one function returning Object
if you don't.
Upvotes: 6