Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic extending class AND implements interface in Kotlin

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?

like image 400
frenchdonuts Avatar asked Dec 26 '15 11:12

frenchdonuts


People also ask

Can a generic class extend an interface?

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.

What is generic class in Kotlin?

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.

How do I extend an interface in Kotlin?

In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface.

How does Kotlin implement 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.


Video Answer


1 Answers

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.

like image 125
hotkey Avatar answered Sep 20 '22 07:09

hotkey