Accept repeated name for generic and non-generic types

Hi,

I’m wondering if could be possible to have same name for interfaces (and other types as well) when there is a generic version and a non-generic version. For example:

interface Contract {
    fun getPersonsInvolved() : List<Person>
}

interface Contract<T: LoanGuarantee>: Contract {
    fun getLoanGuarantees() : List<T>
}

This helps in following SOLID interface segregation principle in cases where semantically makes sense have the both types declared with the same name. Languages such C# allows this but I’m not sure if there is a way to implement this feature in JVM.

I took a look that java implements generics by type erasure and I came to the conclusion that maybe that’s why it is not possible. But, in java we can do something that seems not to be possible in Kotlin:

class Foo<T>
class Bar : Foo

That means: depends on Foo without declare the generic parameter.

Do you know if there is some barrier in Kotlin to implement this or if it is just matter of choice of language design?

As you know, Java implements generics through erasure. That means that if you define a generic type MyType<T>, at runtime you will have a type called MyType. In this case, MyType without the parameter is called a raw type. So if you tried to directly define both a generic MyType<T> and a non-generic MyType, at runtime you would have to classes called MyType, which would result in a name clash.

In Java, it is possible to refer to a raw type directly in the code. This is generally considered bad practice as raw types do not offer the same static type safety as generics. The main (if not only) reason raw types are even allowed to be used in Java is for backwards compatibility, as generics did not exist until Java 5. In Java 5, however, a lot of existing classes and interfaces (including core library types such as List) were made generic. Raw types were a necessary feature in order to not break virtually all Java 1.4 code in existence. As Kotlin is not intended to be source code compatible with Java 1.4, there is not the same need for raw types in Kotlin.

1 Like