Say I want a type variable, T, that extends a certain class and implements an interface. Something like:
class Foo <T : Bar implements Baz> { ... }
What is the syntax for this in Kotlin?
Java Generic Classes and SubtypingWe can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.
Generics means we use a class or an implementation in a very generic manner. For example, the interface List allows us for code reuse. We are able to create a list of Strings, of integer values and we will have the same operations even if we have different types.
In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface.
Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be abstract or provide accessor implementations.
Only one upper bound can be specified inside the angle brackets.
Kotlin offers different syntax for generic constraints when there is more than one constraint:
class Foo<T>(val t: T) where T : Bar, T : Baz { ... }
and for functions:
fun <T> f(): Foo where T : Bar, T : Baz { ... }
It is documented here.
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