I'm trying to derive my class from generic class:
class foo<T> {} class bar : foo<Int> {}
But this code fails to compile with en error:
Classes derived from generic classes must also be generic
How to avoid this limitation? Is it possible?
Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
In the same way, you can derive a generic class from another generic class that derived from a generic interface. You may be tempted to derive just any type of class from it. One of the features of generics is that you can create a class that must implement the functionality of a certain abstract class of your choice.
The generic class works with multiple data types. A normal class works with only one kind of data type.
Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced. Better performance.
Ssreg,
Unfortunately this is official:
You can subclass a generic class, but the subclass must also be a generic class.
Let us hope Apple fixes this in a future version.
Meanwhile, let us see this as an opportunity to exploit aggregation instead of subclassing.
NOTE:
As a poor man's version of a solution, one could use typealias
:
class foo<T> {} class bar<Int> : foo<Int> {} typealias Bar = bar<Int>
This way, the rest of the code can be written just as if Apple already fixed the matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With