Simple Fellow
Simple Fellow

Reputation: 4622

Why this code is not possible in Kotlin?

Below is a perfectly construct in C++, C# and other similar languages. Why this is not possible in Kotlin

open class EndPoint<T> (url: String): T{

...
}

class BlueEndPoint: EndPoint<BlueInterface>{}
class RedEndPoint: EndPoint<RedInterface>{}

Upvotes: 1

Views: 405

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

Because Kotlin uses generics, not templates. It has just one EndPoint class instead of creating a new one for every T like C++ does.

And on JVM this class needs to extend exactly one superclass (possibly Object) and a specific set of interfaces (possibly none). I.e. you can't have EndPoint<BlueInterface> implement BlueInterface but not RedInterface and vice versa for EndPoint<RedInterface>.

According to MSDN it doesn't work in C# either (I believe CLR has the same requirement when defining classes):

C# does not allow the type parameter to be used as the base class for the generic type.

It's C++ which is the exception here.

Upvotes: 8

Aleksei Novikov
Aleksei Novikov

Reputation: 11

It caused by the JVM generics restrictions. More information you can read [here] (https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html).

Upvotes: 1

Related Questions