1

Long story short: having C# experience with explicit interfaces implementation, I tried to do the same on Kotlin and failed (or didn't find a way yet). Situation:

interface IProblem<T> {
    fun solve(t: T)
}

class Puzzle: IProblem<Int>, IProblem<Any> {
    override fun solve(t: Int) {
    }

    override fun solve(t: Any) {
    }
}

As you can see, I have a class which I plan to have as an implementation for the same generic interface applied twice, with two different types T inside. For simplicity, let say they're Int and Any (it doesn't matter, they're just not the same, nor descendant/ancestor to each other).

So, I would expect I can explicitly say "hey, this solve() method is for IProblem<Int> and another solve() is for IProblem<Any>. Surprisingly, all I can get is IDE claiming that two methods have the same JVM signature.

Am I correct there is no such thing as explicit interface implementation in Kotlin and I have to re-think my design? I would imagine something like that:

class Puzzle: IProblem<Int>, IProblem<Any> {
    override fun IProblem<Int>.solve(t: Int) {
    }

    override fun IProblem<Any>.solve(t: Any) {
    }
}
Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42
  • Many languages don't even allow you to overload. Is there a reason you want this? And if you really need it, you could "monomorphize" manually by checking `t is Int` and specifying `t: Any`. – Mateen Ulhaq Jun 19 '20 at 22:19
  • 6
    This will not happen because of type erasure. It would work in C# but it won't work in Java/JVM/Kotlin-JVM. – EpicPandaForce Jun 19 '20 at 23:06
  • 1
    In this particular case, since the only types you support are `Any` and `Int`, you could remove the generics from the interface and have it operate on `Any`, and use `if (t is Int)` in your single `solve` function. – Tenfour04 Jun 20 '20 at 00:31
  • please follow https://stackoverflow.com/q/35528261/4267015 – Naor Tedgi Jun 20 '20 at 07:38

0 Answers0