1

I'm pretty new in Kotlin language, but I have just encountered some strange behavior that didn't have in other languages, so I wanted to ask why I can't do something like this:

fun <T> methodName()
{
    // whatev~ 
}

fun <T, K> methodName()
{
    // whatev~   
}

This code throws an error of "Conflicting overloads".

In other languages, for example C# I can do this and it's a pretty neat trick to have only one method that work for one or multiple types at the same time.

The only workaround I've found it's adding in each new method that I do an optional parameter that I'll never use, like:

fun <T> methodName()
{

}

fun <T, K> methodName(crappyParam: String = "")
{

}
Patroklo
  • 516
  • 4
  • 15
  • 1
    Can you please provide a specific example of what you're trying to accomplish and why you need this? – yole Apr 20 '18 at 06:28
  • Your `` are unused type variables that you don't involve in any part of the method signature. This wouldn't work in any language. Based on what should the compiler choose one or the other? – Marko Topolnik Apr 20 '18 at 09:38
  • Use `@JvmName` to rename one of them... if you really _need_ it to be like this; as yole points out, it's probably not the best idea – Salem Apr 20 '18 at 09:46
  • 1
    @MarkoTopolnik Even for this oversimplified case, you could just have calls with explicit type parameters. – Alexey Romanov Apr 20 '18 at 10:08
  • @AlexeyRomanov I see, just the arity of the explicit params would make the selection. – Marko Topolnik Apr 20 '18 at 10:53

1 Answers1

1

The two methods would have the same signature in JVM type system (which doesn't support generics), which isn't allowed.

A JVM language could "mangle" such methods, e.g. giving them different names in bytecode. A JVM implementation of C# would have to.

But Kotlin doesn't. And doing so would hurt interoperability with Java, which is one of Kotlin's major requirements.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • This is actually not the problem here. Conflicting overloads will be reported even if you use `@JvmName` to assign different names to the methods. – yole Apr 20 '18 at 12:26
  • Then would it be fair to say that while Kotlin explicitly disallows this, it wouldn't if Java allowed? And I believe this is the primary reason why Java doesn't allow it. – Alexey Romanov Apr 20 '18 at 17:32
  • A more useful case than the one in question would be methods like ` first(Tuple pair): T1` and ` first(Tuple triple): T1` if you assume overloading classes on number of type parameters would also be permitted as in CLR languages. – Alexey Romanov Apr 20 '18 at 17:36