Is there a function to create a `Comparable` from ...
# stdlib
c
Is there a function to create a
Comparable
from a
Comparator
? If there is none, I think it would be a nice addition, to make this possible:
Copy code
class Foo(…) : Comparable<Foo> by fooComparator.asComparable() {

    companion object {
        private val fooComparator = compareBy({…}, {…}) // use the stdlib convenience functions for comparators
    }
}
Otherwise, it's not possible to reuse these convenience functions
r
I don't see a way to do this cleanly with delegation, but reusing the convenience function is still possible by simply implementing the interface like this:
Copy code
override fun compareTo(other: Foo): Int = fooComparator.compare(this, other)
Regarding delegation, I think the issue here is that the
compare
method in the Comparable interface needs access to the instance of
Foo
, and I doubt there's a way to access that in a delegate (but maybe I'm mistaken). If comparing by a single property, something like this works:
Copy code
class Foo(val x: Int): Comparable<Int> by x
but that won't work when comparing multiple properties 🙂