1

I'm getting a Platform Declaration Clash error from the compiler resulting from multiple default implementations of the Comparable interfaces (demonstrated below).

interface ClassA: Comparable<ClassA>
{
    val x: Int
        get

    override fun compareTo(other: ClassA): Int = this.x.compareTo(other.x)
}

interface ClassB: Comparable<ClassB>
{
    val y: String
        get

    override fun compareTo(other: ClassB): = this.y.compareTo(other.t)
}

data class ClassAB(val x: Int, val y: String): ClassA, ClassB
{
     ...
}

I understand why I'm getting this error; both default implementations of compareTo map to compareTo(Object) in Java. Thus, in the child, Kotlin doesn't know which one to use.

Is there a mechanism that will allow me to select the one to use, or, better yet, let me override compareTo(Object)? I've tried defining compareTo(Any), but that wasn't right. Another posting suggested using @JvmName, but the annotation doesn't apply here (per the compiler).

Any help would be greatly appreciated. Thanks!

desilvai
  • 331
  • 3
  • 9
  • If you change all your `Comparable` to `Comparable` you could do this, and you would override it with same signature in `ClassAB` ... but then you have to type check the compare and decide what to do if not the same class type. – Jayson Minard Oct 19 '16 at 13:57

1 Answers1

4

Either you have to get rid of one of those comparables or you could use composition. It depends on you use case.

Here is example for composition.

data class ClassAB(val x: Int, val y: String): Comparable<ClassAB>
{
    val classA: ClassA
    val classB: ClassB

    override fun compareTo(other: ClassAB): Int {
        // do compare
        classA.compareTo(other.classA)
        classB.compareTo(other.classB)
        throw UnsupportedOperationException("not implemented")
    }
}
Januson
  • 4,533
  • 34
  • 42
  • 2
    +1. the `compareTo`-implementation simply does not belong into an interface. it's "wrong" to compare things that are not concrete – Lovis Oct 18 '16 at 07:36
  • @Lovis I wouldn't say that, conceptually the interface can say that it can be compared based on the state it expects and it provides a default implementation based on that state. Like any default implementation in an interface it can be overridden by concrete implementations that want to differ. But I do agree in this case it is odd and will cause weird implementation problems. – Jayson Minard Oct 19 '16 at 13:58
  • @JaysonMinard that's why I wrote "wrong" in _"_ ;-) – Lovis Oct 19 '16 at 14:25