Skip to content
Advertisement

How to convert a class A to class B?

I am working on a method where I’ve written the following line here:

JavaScript

As you can see from the TrackingCategoryTransformationClient class below, this yields an error as the abstract method getErpListDataById returns Optional<AccountingObject> and not Optional<TrackingCategory> which is what the variable is expecting.

I cannot change the class that is T is bounded by in the generic since other methods depend on it

Instead, I want to know if it’s possible to convert the AccountingObject object to TrackingCategory instead?

TrackingCategory inherits (extends) from AccountingObject so I tried downcasting by (TrackingCategory) to the trackingCategoryTransformation class but this gave me an “Inconvertible types” error where AccountingObject cannot be cast to TrackingCategory

Thus, I’m trying to understand what I can do to convert the class to TrackingCategory.

TrackingCategoryTransformationClient

JavaScript

Advertisement

Answer

There are two possible solutions (with TrackingCategory extends AccountingObject). The first one is to cast to TrackingCategory.:

JavaScript

You can also filter and map on Optional but it would be empty if not the first but the second entry is a TrackingCategory:

JavaScript

The second solution is to give the compiler a hint of the generic T but you should be sure that all elements are TrackingCategory:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement